github.com/akerouanton/docker@v1.11.0-rc3/integration-cli/docker_cli_run_test.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "bytes" 6 "fmt" 7 "io/ioutil" 8 "net" 9 "os" 10 "os/exec" 11 "path" 12 "path/filepath" 13 "reflect" 14 "regexp" 15 "sort" 16 "strconv" 17 "strings" 18 "sync" 19 "time" 20 21 "github.com/docker/docker/pkg/integration/checker" 22 "github.com/docker/docker/pkg/mount" 23 "github.com/docker/docker/pkg/stringutils" 24 "github.com/docker/docker/runconfig" 25 "github.com/docker/go-connections/nat" 26 "github.com/docker/libnetwork/netutils" 27 "github.com/docker/libnetwork/resolvconf" 28 "github.com/go-check/check" 29 ) 30 31 // "test123" should be printed by docker run 32 func (s *DockerSuite) TestRunEchoStdout(c *check.C) { 33 out, _ := dockerCmd(c, "run", "busybox", "echo", "test123") 34 if out != "test123\n" { 35 c.Fatalf("container should've printed 'test123', got '%s'", out) 36 } 37 } 38 39 // "test" should be printed 40 func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) { 41 out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test") 42 if out != "test\n" { 43 c.Errorf("container should've printed 'test'") 44 } 45 } 46 47 // docker run should not leak file descriptors. This test relies on Unix 48 // specific functionality and cannot run on Windows. 49 func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) { 50 testRequires(c, DaemonIsLinux) 51 out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd") 52 53 // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory 54 if out != "0 1 2 3\n" { 55 c.Errorf("container should've printed '0 1 2 3', not: %s", out) 56 } 57 } 58 59 // it should be possible to lookup Google DNS 60 // this will fail when Internet access is unavailable 61 func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) { 62 testRequires(c, Network, NotArm) 63 image := DefaultImage 64 if daemonPlatform == "windows" { 65 // nslookup isn't present in Windows busybox. Is built-in. 66 image = WindowsBaseImage 67 } 68 dockerCmd(c, "run", image, "nslookup", "google.com") 69 } 70 71 // the exit code should be 0 72 func (s *DockerSuite) TestRunExitCodeZero(c *check.C) { 73 dockerCmd(c, "run", "busybox", "true") 74 } 75 76 // the exit code should be 1 77 func (s *DockerSuite) TestRunExitCodeOne(c *check.C) { 78 _, exitCode, err := dockerCmdWithError("run", "busybox", "false") 79 if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) { 80 c.Fatal(err) 81 } 82 if exitCode != 1 { 83 c.Errorf("container should've exited with exit code 1. Got %d", exitCode) 84 } 85 } 86 87 // it should be possible to pipe in data via stdin to a process running in a container 88 func (s *DockerSuite) TestRunStdinPipe(c *check.C) { 89 // TODO Windows: This needs some work to make compatible. 90 testRequires(c, DaemonIsLinux) 91 runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat") 92 runCmd.Stdin = strings.NewReader("blahblah") 93 out, _, _, err := runCommandWithStdoutStderr(runCmd) 94 if err != nil { 95 c.Fatalf("failed to run container: %v, output: %q", err, out) 96 } 97 98 out = strings.TrimSpace(out) 99 dockerCmd(c, "wait", out) 100 101 logsOut, _ := dockerCmd(c, "logs", out) 102 103 containerLogs := strings.TrimSpace(logsOut) 104 if containerLogs != "blahblah" { 105 c.Errorf("logs didn't print the container's logs %s", containerLogs) 106 } 107 108 dockerCmd(c, "rm", out) 109 } 110 111 // the container's ID should be printed when starting a container in detached mode 112 func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) { 113 out, _ := dockerCmd(c, "run", "-d", "busybox", "true") 114 115 out = strings.TrimSpace(out) 116 dockerCmd(c, "wait", out) 117 118 rmOut, _ := dockerCmd(c, "rm", out) 119 120 rmOut = strings.TrimSpace(rmOut) 121 if rmOut != out { 122 c.Errorf("rm didn't print the container ID %s %s", out, rmOut) 123 } 124 } 125 126 // the working directory should be set correctly 127 func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) { 128 // TODO Windows: There's a Windows bug stopping this from working. 129 testRequires(c, DaemonIsLinux) 130 dir := "/root" 131 image := "busybox" 132 if daemonPlatform == "windows" { 133 dir = `/windows` 134 image = WindowsBaseImage 135 } 136 137 // First with -w 138 out, _ := dockerCmd(c, "run", "-w", dir, image, "pwd") 139 out = strings.TrimSpace(out) 140 if out != dir { 141 c.Errorf("-w failed to set working directory") 142 } 143 144 // Then with --workdir 145 out, _ = dockerCmd(c, "run", "--workdir", dir, image, "pwd") 146 out = strings.TrimSpace(out) 147 if out != dir { 148 c.Errorf("--workdir failed to set working directory") 149 } 150 } 151 152 // pinging Google's DNS resolver should fail when we disable the networking 153 func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) { 154 count := "-c" 155 image := "busybox" 156 if daemonPlatform == "windows" { 157 count = "-n" 158 image = WindowsBaseImage 159 } 160 161 // First using the long form --net 162 out, exitCode, err := dockerCmdWithError("run", "--net=none", image, "ping", count, "1", "8.8.8.8") 163 if err != nil && exitCode != 1 { 164 c.Fatal(out, err) 165 } 166 if exitCode != 1 { 167 c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8") 168 } 169 } 170 171 //test --link use container name to link target 172 func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) { 173 // TODO Windows: This test cannot run on a Windows daemon as the networking 174 // settings are not populated back yet on inspect. 175 testRequires(c, DaemonIsLinux) 176 dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox") 177 178 ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress") 179 180 out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts") 181 if !strings.Contains(out, ip+" test") { 182 c.Fatalf("use a container name to link target failed") 183 } 184 } 185 186 //test --link use container id to link target 187 func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) { 188 // TODO Windows: This test cannot run on a Windows daemon as the networking 189 // settings are not populated back yet on inspect. 190 testRequires(c, DaemonIsLinux) 191 cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox") 192 193 cID = strings.TrimSpace(cID) 194 ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress") 195 196 out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts") 197 if !strings.Contains(out, ip+" test") { 198 c.Fatalf("use a container id to link target failed") 199 } 200 } 201 202 func (s *DockerSuite) TestUserDefinedNetworkLinks(c *check.C) { 203 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 204 dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") 205 206 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") 207 c.Assert(waitRun("first"), check.IsNil) 208 209 // run a container in user-defined network udlinkNet with a link for an existing container 210 // and a link for a container that doesn't exist 211 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", 212 "--link=third:bar", "busybox", "top") 213 c.Assert(waitRun("second"), check.IsNil) 214 215 // ping to first and its alias foo must succeed 216 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 217 c.Assert(err, check.IsNil) 218 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 219 c.Assert(err, check.IsNil) 220 221 // ping to third and its alias must fail 222 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") 223 c.Assert(err, check.NotNil) 224 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") 225 c.Assert(err, check.NotNil) 226 227 // start third container now 228 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top") 229 c.Assert(waitRun("third"), check.IsNil) 230 231 // ping to third and its alias must succeed now 232 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") 233 c.Assert(err, check.IsNil) 234 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") 235 c.Assert(err, check.IsNil) 236 } 237 238 func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) { 239 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 240 dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") 241 242 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") 243 c.Assert(waitRun("first"), check.IsNil) 244 245 dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", 246 "busybox", "top") 247 c.Assert(waitRun("second"), check.IsNil) 248 249 // ping to first and its alias foo must succeed 250 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 251 c.Assert(err, check.IsNil) 252 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 253 c.Assert(err, check.IsNil) 254 255 // Restart first container 256 dockerCmd(c, "restart", "first") 257 c.Assert(waitRun("first"), check.IsNil) 258 259 // ping to first and its alias foo must still succeed 260 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 261 c.Assert(err, check.IsNil) 262 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 263 c.Assert(err, check.IsNil) 264 265 // Restart second container 266 dockerCmd(c, "restart", "second") 267 c.Assert(waitRun("second"), check.IsNil) 268 269 // ping to first and its alias foo must still succeed 270 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 271 c.Assert(err, check.IsNil) 272 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") 273 c.Assert(err, check.IsNil) 274 } 275 276 func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *check.C) { 277 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 278 279 defaults := []string{"bridge", "host", "none"} 280 for _, net := range defaults { 281 out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top") 282 c.Assert(err, checker.NotNil) 283 c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error()) 284 } 285 } 286 287 func (s *DockerSuite) TestUserDefinedNetworkAlias(c *check.C) { 288 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 289 dockerCmd(c, "network", "create", "-d", "bridge", "net1") 290 291 dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox", "top") 292 c.Assert(waitRun("first"), check.IsNil) 293 294 dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top") 295 c.Assert(waitRun("second"), check.IsNil) 296 297 // ping to first and its network-scoped aliases 298 _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 299 c.Assert(err, check.IsNil) 300 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") 301 c.Assert(err, check.IsNil) 302 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") 303 c.Assert(err, check.IsNil) 304 305 // Restart first container 306 dockerCmd(c, "restart", "first") 307 c.Assert(waitRun("first"), check.IsNil) 308 309 // ping to first and its network-scoped aliases must succeed 310 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") 311 c.Assert(err, check.IsNil) 312 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") 313 c.Assert(err, check.IsNil) 314 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") 315 c.Assert(err, check.IsNil) 316 } 317 318 // Issue 9677. 319 func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) { 320 out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true") 321 if err != nil { 322 if !strings.Contains(out, "flag provided but not defined: --exec-opt") { // no daemon (client-only) 323 c.Fatal(err, out) 324 } 325 } 326 } 327 328 // Regression test for #4979 329 func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) { 330 331 var ( 332 out string 333 exitCode int 334 ) 335 336 // Create a file in a volume 337 if daemonPlatform == "windows" { 338 out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, WindowsBaseImage, `cmd /c echo hello > c:\some\dir\file`) 339 } else { 340 out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") 341 } 342 if exitCode != 0 { 343 c.Fatal("1", out, exitCode) 344 } 345 346 // Read the file from another container using --volumes-from to access the volume in the second container 347 if daemonPlatform == "windows" { 348 out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", WindowsBaseImage, `cmd /c type c:\some\dir\file`) 349 } else { 350 out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") 351 } 352 if exitCode != 0 { 353 c.Fatal("2", out, exitCode) 354 } 355 } 356 357 // Volume path is a symlink which also exists on the host, and the host side is a file not a dir 358 // But the volume call is just a normal volume, not a bind mount 359 func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) { 360 var ( 361 dockerFile string 362 containerPath string 363 cmd string 364 ) 365 testRequires(c, SameHostDaemon) 366 name := "test-volume-symlink" 367 368 dir, err := ioutil.TempDir("", name) 369 if err != nil { 370 c.Fatal(err) 371 } 372 defer os.RemoveAll(dir) 373 374 // In the case of Windows to Windows CI, if the machine is setup so that 375 // the temp directory is not the C: drive, this test is invalid and will 376 // not work. 377 if daemonPlatform == "windows" && strings.ToLower(dir[:1]) != "c" { 378 c.Skip("Requires TEMP to point to C: drive") 379 } 380 381 f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700) 382 if err != nil { 383 c.Fatal(err) 384 } 385 f.Close() 386 387 if daemonPlatform == "windows" { 388 dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", WindowsBaseImage, dir, dir) 389 containerPath = `c:\test\test` 390 cmd = "tasklist" 391 } else { 392 dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir) 393 containerPath = "/test/test" 394 cmd = "true" 395 } 396 if _, err := buildImage(name, dockerFile, false); err != nil { 397 c.Fatal(err) 398 } 399 400 dockerCmd(c, "run", "-v", containerPath, name, cmd) 401 } 402 403 // Volume path is a symlink in the container 404 func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *check.C) { 405 var ( 406 dockerFile string 407 containerPath string 408 cmd string 409 ) 410 testRequires(c, SameHostDaemon) 411 name := "test-volume-symlink2" 412 413 if daemonPlatform == "windows" { 414 dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", WindowsBaseImage, name, name) 415 containerPath = `c:\test\test` 416 cmd = "tasklist" 417 } else { 418 dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p /%s\nRUN ln -s /%s /test", name, name) 419 containerPath = "/test/test" 420 cmd = "true" 421 } 422 if _, err := buildImage(name, dockerFile, false); err != nil { 423 c.Fatal(err) 424 } 425 426 dockerCmd(c, "run", "-v", containerPath, name, cmd) 427 } 428 429 func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) { 430 // TODO Windows (Post TP4): This test cannot run on a Windows daemon as 431 // Windows does not support read-only bind mounts. 432 testRequires(c, DaemonIsLinux) 433 if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 { 434 c.Fatalf("run should fail because volume is ro: exit code %d", code) 435 } 436 } 437 438 func (s *DockerSuite) TestRunVolumesFromInReadonlyModeFails(c *check.C) { 439 // TODO Windows (Post TP4): This test cannot run on a Windows daemon as 440 // Windows does not support read-only bind mounts. Modified for when ro is supported. 441 testRequires(c, DaemonIsLinux) 442 var ( 443 volumeDir string 444 fileInVol string 445 ) 446 if daemonPlatform == "windows" { 447 volumeDir = `c:/test` // Forward-slash as using busybox 448 fileInVol = `c:/test/file` 449 } else { 450 testRequires(c, DaemonIsLinux) 451 volumeDir = "/test" 452 fileInVol = `/test/file` 453 } 454 dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") 455 456 if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 { 457 c.Fatalf("run should fail because volume is ro: exit code %d", code) 458 } 459 } 460 461 // Regression test for #1201 462 func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) { 463 var ( 464 volumeDir string 465 fileInVol string 466 ) 467 if daemonPlatform == "windows" { 468 volumeDir = `c:/test` // Forward-slash as using busybox 469 fileInVol = `c:/test/file` 470 } else { 471 volumeDir = "/test" 472 fileInVol = "/test/file" 473 } 474 475 dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") 476 dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol) 477 478 if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) { 479 c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out) 480 } 481 482 dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol) 483 } 484 485 func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) { 486 // TODO Windows: This test cannot yet run on a Windows daemon as Windows does 487 // not support read-only bind mounts as at TP4 488 testRequires(c, DaemonIsLinux) 489 dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true") 490 491 // Expect this "rw" mode to be be ignored since the inherited volume is "ro" 492 if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil { 493 c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`") 494 } 495 496 dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true") 497 498 // Expect this to be read-only since both are "ro" 499 if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil { 500 c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`") 501 } 502 } 503 504 // Test for GH#10618 505 func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) { 506 path1 := randomTmpDirPath("test1", daemonPlatform) 507 path2 := randomTmpDirPath("test2", daemonPlatform) 508 509 someplace := ":/someplace" 510 if daemonPlatform == "windows" { 511 // Windows requires that the source directory exists before calling HCS 512 testRequires(c, SameHostDaemon) 513 someplace = `:c:\someplace` 514 if err := os.MkdirAll(path1, 0755); err != nil { 515 c.Fatalf("Failed to create %s: %q", path1, err) 516 } 517 defer os.RemoveAll(path1) 518 if err := os.MkdirAll(path2, 0755); err != nil { 519 c.Fatalf("Failed to create %s: %q", path1, err) 520 } 521 defer os.RemoveAll(path2) 522 } 523 mountstr1 := path1 + someplace 524 mountstr2 := path2 + someplace 525 526 if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil { 527 c.Fatal("Expected error about duplicate mount definitions") 528 } else { 529 if !strings.Contains(out, "Duplicate mount point") { 530 c.Fatalf("Expected 'duplicate mount point' error, got %v", out) 531 } 532 } 533 } 534 535 // Test for #1351 536 func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) { 537 prefix := "" 538 if daemonPlatform == "windows" { 539 prefix = `c:` 540 } 541 dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") 542 dockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo") 543 } 544 545 func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) { 546 prefix := "" 547 if daemonPlatform == "windows" { 548 prefix = `c:` 549 } 550 dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") 551 dockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar") 552 dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar") 553 } 554 555 // this tests verifies the ID format for the container 556 func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) { 557 out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true") 558 if err != nil { 559 c.Fatal(err) 560 } 561 if exit != 0 { 562 c.Fatalf("expected exit code 0 received %d", exit) 563 } 564 565 match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n")) 566 if err != nil { 567 c.Fatal(err) 568 } 569 if !match { 570 c.Fatalf("Invalid container ID: %s", out) 571 } 572 } 573 574 // Test that creating a container with a volume doesn't crash. Regression test for #995. 575 func (s *DockerSuite) TestRunCreateVolume(c *check.C) { 576 prefix := "" 577 if daemonPlatform == "windows" { 578 prefix = `c:` 579 } 580 dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true") 581 } 582 583 // Test that creating a volume with a symlink in its path works correctly. Test for #5152. 584 // Note that this bug happens only with symlinks with a target that starts with '/'. 585 func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) { 586 // Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...) 587 testRequires(c, DaemonIsLinux) 588 image := "docker-test-createvolumewithsymlink" 589 590 buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-") 591 buildCmd.Stdin = strings.NewReader(`FROM busybox 592 RUN ln -s home /bar`) 593 buildCmd.Dir = workingDirectory 594 err := buildCmd.Run() 595 if err != nil { 596 c.Fatalf("could not build '%s': %v", image, err) 597 } 598 599 _, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo") 600 if err != nil || exitCode != 0 { 601 c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) 602 } 603 604 volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo") 605 c.Assert(err, checker.IsNil) 606 607 _, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink") 608 if err != nil || exitCode != 0 { 609 c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode) 610 } 611 612 _, err = os.Stat(volPath) 613 if !os.IsNotExist(err) { 614 c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath) 615 } 616 } 617 618 // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`. 619 func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) { 620 name := "docker-test-volumesfromsymlinkpath" 621 prefix := "" 622 dfContents := `FROM busybox 623 RUN ln -s home /foo 624 VOLUME ["/foo/bar"]` 625 626 if daemonPlatform == "windows" { 627 prefix = `c:` 628 dfContents = `FROM ` + WindowsBaseImage + ` 629 RUN mkdir c:\home 630 RUN mklink /D c:\foo c:\home 631 VOLUME ["c:/foo/bar"] 632 ENTRYPOINT c:\windows\system32\cmd.exe` 633 } 634 635 buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-") 636 buildCmd.Stdin = strings.NewReader(dfContents) 637 buildCmd.Dir = workingDirectory 638 err := buildCmd.Run() 639 if err != nil { 640 c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err) 641 } 642 643 out, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name) 644 if err != nil || exitCode != 0 { 645 c.Fatalf("[run] (volume) err: %v, exitcode: %d, out: %s", err, exitCode, out) 646 } 647 648 _, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls "+prefix+"/foo | grep -q bar") 649 if err != nil || exitCode != 0 { 650 c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) 651 } 652 } 653 654 func (s *DockerSuite) TestRunExitCode(c *check.C) { 655 var ( 656 exit int 657 err error 658 ) 659 660 _, exit, err = dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72") 661 662 if err == nil { 663 c.Fatal("should not have a non nil error") 664 } 665 if exit != 72 { 666 c.Fatalf("expected exit code 72 received %d", exit) 667 } 668 } 669 670 func (s *DockerSuite) TestRunUserDefaults(c *check.C) { 671 expected := "uid=0(root) gid=0(root)" 672 if daemonPlatform == "windows" { 673 // TODO Windows: Remove this check once TP4 is no longer supported. 674 if windowsDaemonKV < 14250 { 675 expected = "uid=1000(SYSTEM) gid=1000(SYSTEM)" 676 } else { 677 expected = "uid=1000(ContainerAdministrator) gid=1000(ContainerAdministrator)" 678 } 679 } 680 out, _ := dockerCmd(c, "run", "busybox", "id") 681 if !strings.Contains(out, expected) { 682 c.Fatalf("expected '%s' got %s", expected, out) 683 } 684 } 685 686 func (s *DockerSuite) TestRunUserByName(c *check.C) { 687 // TODO Windows: This test cannot run on a Windows daemon as Windows does 688 // not support the use of -u 689 testRequires(c, DaemonIsLinux) 690 out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id") 691 if !strings.Contains(out, "uid=0(root) gid=0(root)") { 692 c.Fatalf("expected root user got %s", out) 693 } 694 } 695 696 func (s *DockerSuite) TestRunUserByID(c *check.C) { 697 // TODO Windows: This test cannot run on a Windows daemon as Windows does 698 // not support the use of -u 699 testRequires(c, DaemonIsLinux) 700 out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id") 701 if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { 702 c.Fatalf("expected daemon user got %s", out) 703 } 704 } 705 706 func (s *DockerSuite) TestRunUserByIDBig(c *check.C) { 707 // TODO Windows: This test cannot run on a Windows daemon as Windows does 708 // not support the use of -u 709 testRequires(c, DaemonIsLinux, NotArm) 710 out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id") 711 if err == nil { 712 c.Fatal("No error, but must be.", out) 713 } 714 if !strings.Contains(out, "Uids and gids must be in range") { 715 c.Fatalf("expected error about uids range, got %s", out) 716 } 717 } 718 719 func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) { 720 // TODO Windows: This test cannot run on a Windows daemon as Windows does 721 // not support the use of -u 722 testRequires(c, DaemonIsLinux) 723 out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id") 724 if err == nil { 725 c.Fatal("No error, but must be.", out) 726 } 727 if !strings.Contains(out, "Uids and gids must be in range") { 728 c.Fatalf("expected error about uids range, got %s", out) 729 } 730 } 731 732 func (s *DockerSuite) TestRunUserByIDZero(c *check.C) { 733 // TODO Windows: This test cannot run on a Windows daemon as Windows does 734 // not support the use of -u 735 testRequires(c, DaemonIsLinux) 736 out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id") 737 if err != nil { 738 c.Fatal(err, out) 739 } 740 if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") { 741 c.Fatalf("expected daemon user got %s", out) 742 } 743 } 744 745 func (s *DockerSuite) TestRunUserNotFound(c *check.C) { 746 // TODO Windows: This test cannot run on a Windows daemon as Windows does 747 // not support the use of -u 748 testRequires(c, DaemonIsLinux) 749 _, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id") 750 if err == nil { 751 c.Fatal("unknown user should cause container to fail") 752 } 753 } 754 755 func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) { 756 // TODO Windows. There are two bugs in TP4 which means this test cannot 757 // be reliably enabled. The first is a race condition where sometimes 758 // HCS CreateComputeSystem() will fail "Invalid class string". #4985252 and 759 // #4493430. 760 // 761 // The second, which is seen more readily by increasing the number of concurrent 762 // containers to 5 or more, is that CSRSS hangs. This may fixed in the TP4 ZDP. 763 // #4898773. 764 testRequires(c, DaemonIsLinux) 765 sleepTime := "2" 766 if daemonPlatform == "windows" { 767 sleepTime = "5" // Make more reliable on Windows 768 } 769 group := sync.WaitGroup{} 770 group.Add(2) 771 772 errChan := make(chan error, 2) 773 for i := 0; i < 2; i++ { 774 go func() { 775 defer group.Done() 776 _, _, err := dockerCmdWithError("run", "busybox", "sleep", sleepTime) 777 errChan <- err 778 }() 779 } 780 781 group.Wait() 782 close(errChan) 783 784 for err := range errChan { 785 c.Assert(err, check.IsNil) 786 } 787 } 788 789 func (s *DockerSuite) TestRunEnvironment(c *check.C) { 790 // TODO Windows: Environment handling is different between Linux and 791 // Windows and this test relies currently on unix functionality. 792 testRequires(c, DaemonIsLinux) 793 cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env") 794 cmd.Env = append(os.Environ(), 795 "TRUE=false", 796 "TRICKY=tri\ncky\n", 797 ) 798 799 out, _, err := runCommandWithOutput(cmd) 800 if err != nil { 801 c.Fatal(err, out) 802 } 803 804 actualEnv := strings.Split(strings.TrimSpace(out), "\n") 805 sort.Strings(actualEnv) 806 807 goodEnv := []string{ 808 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 809 "HOSTNAME=testing", 810 "FALSE=true", 811 "TRUE=false", 812 "TRICKY=tri", 813 "cky", 814 "", 815 "HOME=/root", 816 } 817 sort.Strings(goodEnv) 818 if len(goodEnv) != len(actualEnv) { 819 c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", ")) 820 } 821 for i := range goodEnv { 822 if actualEnv[i] != goodEnv[i] { 823 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 824 } 825 } 826 } 827 828 func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) { 829 // TODO Windows: Environment handling is different between Linux and 830 // Windows and this test relies currently on unix functionality. 831 testRequires(c, DaemonIsLinux) 832 833 // Test to make sure that when we use -e on env vars that are 834 // not set in our local env that they're removed (if present) in 835 // the container 836 837 cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env") 838 cmd.Env = appendBaseEnv(true) 839 840 out, _, err := runCommandWithOutput(cmd) 841 if err != nil { 842 c.Fatal(err, out) 843 } 844 845 actualEnv := strings.Split(strings.TrimSpace(out), "\n") 846 sort.Strings(actualEnv) 847 848 goodEnv := []string{ 849 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 850 "HOME=/root", 851 } 852 sort.Strings(goodEnv) 853 if len(goodEnv) != len(actualEnv) { 854 c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", ")) 855 } 856 for i := range goodEnv { 857 if actualEnv[i] != goodEnv[i] { 858 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 859 } 860 } 861 } 862 863 func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) { 864 // TODO Windows: Environment handling is different between Linux and 865 // Windows and this test relies currently on unix functionality. 866 testRequires(c, DaemonIsLinux) 867 868 // Test to make sure that when we use -e on env vars that are 869 // already in the env that we're overriding them 870 871 cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env") 872 cmd.Env = appendBaseEnv(true, "HOSTNAME=bar") 873 874 out, _, err := runCommandWithOutput(cmd) 875 if err != nil { 876 c.Fatal(err, out) 877 } 878 879 actualEnv := strings.Split(strings.TrimSpace(out), "\n") 880 sort.Strings(actualEnv) 881 882 goodEnv := []string{ 883 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 884 "HOME=/root2", 885 "HOSTNAME=bar", 886 } 887 sort.Strings(goodEnv) 888 if len(goodEnv) != len(actualEnv) { 889 c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", ")) 890 } 891 for i := range goodEnv { 892 if actualEnv[i] != goodEnv[i] { 893 c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) 894 } 895 } 896 } 897 898 func (s *DockerSuite) TestRunContainerNetwork(c *check.C) { 899 if daemonPlatform == "windows" { 900 // Windows busybox does not have ping. Use built in ping instead. 901 dockerCmd(c, "run", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1") 902 } else { 903 dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1") 904 } 905 } 906 907 func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) { 908 // TODO Windows: This is Linux specific as --link is not supported and 909 // this will be deprecated in favor of container networking model. 910 testRequires(c, DaemonIsLinux, NotUserNamespace) 911 dockerCmd(c, "run", "--name", "linked", "busybox", "true") 912 913 _, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true") 914 if err == nil { 915 c.Fatal("Expected error") 916 } 917 } 918 919 // #7851 hostname outside container shows FQDN, inside only shortname 920 // For testing purposes it is not required to set host's hostname directly 921 // and use "--net=host" (as the original issue submitter did), as the same 922 // codepath is executed with "docker run -h <hostname>". Both were manually 923 // tested, but this testcase takes the simpler path of using "run -h .." 924 func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) { 925 // TODO Windows: -h is not yet functional. 926 testRequires(c, DaemonIsLinux) 927 out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname") 928 if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" { 929 c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual) 930 } 931 } 932 933 func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) { 934 // Not applicable for Windows as Windows daemon does not support 935 // the concept of --privileged, and mknod is a Unix concept. 936 testRequires(c, DaemonIsLinux, NotUserNamespace) 937 out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 938 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 939 c.Fatalf("expected output ok received %s", actual) 940 } 941 } 942 943 func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) { 944 // Not applicable for Windows as Windows daemon does not support 945 // the concept of --privileged, and mknod is a Unix concept. 946 testRequires(c, DaemonIsLinux, NotUserNamespace) 947 out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 948 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 949 c.Fatalf("expected output ok received %s", actual) 950 } 951 } 952 953 func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) { 954 // Not applicable for Windows as there is no concept of --cap-drop 955 testRequires(c, DaemonIsLinux) 956 out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls") 957 if err == nil { 958 c.Fatal(err, out) 959 } 960 } 961 962 func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) { 963 // Not applicable for Windows as there is no concept of --cap-drop or mknod 964 testRequires(c, DaemonIsLinux) 965 out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 966 967 if err == nil { 968 c.Fatal(err, out) 969 } 970 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 971 c.Fatalf("expected output not ok received %s", actual) 972 } 973 } 974 975 func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) { 976 // Not applicable for Windows as there is no concept of --cap-drop or mknod 977 testRequires(c, DaemonIsLinux) 978 out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 979 980 if err == nil { 981 c.Fatal(err, out) 982 } 983 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 984 c.Fatalf("expected output not ok received %s", actual) 985 } 986 } 987 988 func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) { 989 // Not applicable for Windows as there is no concept of --cap-drop or mknod 990 testRequires(c, DaemonIsLinux) 991 out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 992 if err == nil { 993 c.Fatal(err, out) 994 } 995 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 996 c.Fatalf("expected output not ok received %s", actual) 997 } 998 } 999 1000 func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) { 1001 // Not applicable for Windows as there is no concept of --cap-drop or mknod 1002 testRequires(c, DaemonIsLinux, NotUserNamespace) 1003 out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") 1004 1005 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1006 c.Fatalf("expected output ok received %s", actual) 1007 } 1008 } 1009 1010 func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) { 1011 // Not applicable for Windows as there is no concept of --cap-add 1012 testRequires(c, DaemonIsLinux) 1013 out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls") 1014 if err == nil { 1015 c.Fatal(err, out) 1016 } 1017 } 1018 1019 func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) { 1020 // Not applicable for Windows as there is no concept of --cap-add 1021 testRequires(c, DaemonIsLinux) 1022 out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1023 1024 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1025 c.Fatalf("expected output ok received %s", actual) 1026 } 1027 } 1028 1029 func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) { 1030 // Not applicable for Windows as there is no concept of --cap-add 1031 testRequires(c, DaemonIsLinux) 1032 out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1033 1034 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1035 c.Fatalf("expected output ok received %s", actual) 1036 } 1037 } 1038 1039 func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) { 1040 // Not applicable for Windows as there is no concept of --cap-add 1041 testRequires(c, DaemonIsLinux) 1042 out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") 1043 if err == nil { 1044 c.Fatal(err, out) 1045 } 1046 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1047 c.Fatalf("expected output not ok received %s", actual) 1048 } 1049 } 1050 1051 func (s *DockerSuite) TestRunGroupAdd(c *check.C) { 1052 // Not applicable for Windows as there is no concept of --group-add 1053 testRequires(c, DaemonIsLinux) 1054 out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id") 1055 1056 groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777" 1057 if actual := strings.Trim(out, "\r\n"); actual != groupsList { 1058 c.Fatalf("expected output %s received %s", groupsList, actual) 1059 } 1060 } 1061 1062 func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) { 1063 // Not applicable for Windows as there is no concept of --privileged 1064 testRequires(c, DaemonIsLinux, NotUserNamespace) 1065 out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") 1066 1067 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 1068 c.Fatalf("expected output ok received %s", actual) 1069 } 1070 } 1071 1072 func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) { 1073 // Not applicable for Windows as there is no concept of unprivileged 1074 testRequires(c, DaemonIsLinux) 1075 out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") 1076 1077 if err == nil { 1078 c.Fatal(err, out) 1079 } 1080 if actual := strings.Trim(out, "\r\n"); actual == "ok" { 1081 c.Fatalf("expected output not ok received %s", actual) 1082 } 1083 } 1084 1085 func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) { 1086 // Not applicable for Windows as there is no concept of unprivileged 1087 testRequires(c, DaemonIsLinux, NotArm) 1088 if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 { 1089 c.Fatal("sys should not be writable in a non privileged container") 1090 } 1091 } 1092 1093 func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) { 1094 // Not applicable for Windows as there is no concept of unprivileged 1095 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 1096 if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 { 1097 c.Fatalf("sys should be writable in privileged container") 1098 } 1099 } 1100 1101 func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) { 1102 // Not applicable for Windows as there is no concept of unprivileged 1103 testRequires(c, DaemonIsLinux) 1104 if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 { 1105 c.Fatal("proc should not be writable in a non privileged container") 1106 } 1107 } 1108 1109 func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) { 1110 // Not applicable for Windows as there is no concept of --privileged 1111 testRequires(c, DaemonIsLinux, NotUserNamespace) 1112 if _, code := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "umount /proc/sysrq-trigger && touch /proc/sysrq-trigger"); code != 0 { 1113 c.Fatalf("proc should be writable in privileged container") 1114 } 1115 } 1116 1117 func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) { 1118 // Not applicable on Windows as /dev/ is a Unix specific concept 1119 // TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user 1120 testRequires(c, DaemonIsLinux, NotUserNamespace) 1121 out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null") 1122 deviceLineFields := strings.Fields(out) 1123 deviceLineFields[6] = "" 1124 deviceLineFields[7] = "" 1125 deviceLineFields[8] = "" 1126 expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"} 1127 1128 if !(reflect.DeepEqual(deviceLineFields, expected)) { 1129 c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out) 1130 } 1131 } 1132 1133 func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) { 1134 // Not applicable on Windows as /dev/ is a Unix specific concept 1135 testRequires(c, DaemonIsLinux) 1136 out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero") 1137 if actual := strings.Trim(out, "\r\n"); actual[0] == '0' { 1138 c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual) 1139 } 1140 } 1141 1142 func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) { 1143 // Not applicable on Windows as it does not support chroot 1144 testRequires(c, DaemonIsLinux) 1145 dockerCmd(c, "run", "busybox", "chroot", "/", "true") 1146 } 1147 1148 func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) { 1149 // Not applicable on Windows as Windows does not support --device 1150 testRequires(c, DaemonIsLinux, NotUserNamespace) 1151 out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo") 1152 if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" { 1153 c.Fatalf("expected output /dev/nulo, received %s", actual) 1154 } 1155 } 1156 1157 func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *check.C) { 1158 // Not applicable on Windows as Windows does not support --device 1159 testRequires(c, DaemonIsLinux, NotUserNamespace) 1160 out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero") 1161 if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" { 1162 c.Fatalf("expected output /dev/zero, received %s", actual) 1163 } 1164 } 1165 1166 func (s *DockerSuite) TestRunAddingOptionalDevicesInvalidMode(c *check.C) { 1167 // Not applicable on Windows as Windows does not support --device 1168 testRequires(c, DaemonIsLinux, NotUserNamespace) 1169 _, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero") 1170 if err == nil { 1171 c.Fatalf("run container with device mode ro should fail") 1172 } 1173 } 1174 1175 func (s *DockerSuite) TestRunModeHostname(c *check.C) { 1176 // Not applicable on Windows as Windows does not support -h 1177 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 1178 1179 out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname") 1180 1181 if actual := strings.Trim(out, "\r\n"); actual != "testhostname" { 1182 c.Fatalf("expected 'testhostname', but says: %q", actual) 1183 } 1184 1185 out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname") 1186 1187 hostname, err := os.Hostname() 1188 if err != nil { 1189 c.Fatal(err) 1190 } 1191 if actual := strings.Trim(out, "\r\n"); actual != hostname { 1192 c.Fatalf("expected %q, but says: %q", hostname, actual) 1193 } 1194 } 1195 1196 func (s *DockerSuite) TestRunRootWorkdir(c *check.C) { 1197 out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd") 1198 expected := "/\n" 1199 if daemonPlatform == "windows" { 1200 expected = "C:" + expected 1201 } 1202 if out != expected { 1203 c.Fatalf("pwd returned %q (expected %s)", s, expected) 1204 } 1205 } 1206 1207 func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) { 1208 if daemonPlatform == "windows" { 1209 // Windows busybox will fail with Permission Denied on items such as pagefile.sys 1210 dockerCmd(c, "run", "-v", `c:\:c:\host`, WindowsBaseImage, "cmd", "-c", "dir", `c:\host`) 1211 } else { 1212 dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host") 1213 } 1214 } 1215 1216 func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) { 1217 mount := "/:/" 1218 targetDir := "/host" 1219 if daemonPlatform == "windows" { 1220 mount = `c:\:c\` 1221 targetDir = "c:/host" // Forward slash as using busybox 1222 } 1223 out, _, err := dockerCmdWithError("run", "-v", mount, "busybox", "ls", targetDir) 1224 if err == nil { 1225 c.Fatal(out, err) 1226 } 1227 } 1228 1229 // Verify that a container gets default DNS when only localhost resolvers exist 1230 func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) { 1231 // Not applicable on Windows as this is testing Unix specific functionality 1232 testRequires(c, SameHostDaemon, DaemonIsLinux) 1233 1234 // preserve original resolv.conf for restoring after test 1235 origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") 1236 if os.IsNotExist(err) { 1237 c.Fatalf("/etc/resolv.conf does not exist") 1238 } 1239 // defer restored original conf 1240 defer func() { 1241 if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil { 1242 c.Fatal(err) 1243 } 1244 }() 1245 1246 // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost 1247 // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by 1248 // GetNameservers(), leading to a replacement of nameservers with the default set 1249 tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1") 1250 if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { 1251 c.Fatal(err) 1252 } 1253 1254 actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") 1255 // check that the actual defaults are appended to the commented out 1256 // localhost resolver (which should be preserved) 1257 // NOTE: if we ever change the defaults from google dns, this will break 1258 expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n" 1259 if actual != expected { 1260 c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual) 1261 } 1262 } 1263 1264 func (s *DockerSuite) TestRunDnsOptions(c *check.C) { 1265 // Not applicable on Windows as Windows does not support --dns*, or 1266 // the Unix-specific functionality of resolv.conf. 1267 testRequires(c, DaemonIsLinux) 1268 out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "--dns-opt=ndots:9", "busybox", "cat", "/etc/resolv.conf") 1269 1270 // The client will get a warning on stderr when setting DNS to a localhost address; verify this: 1271 if !strings.Contains(stderr, "Localhost DNS setting") { 1272 c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr) 1273 } 1274 1275 actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1) 1276 if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" { 1277 c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual) 1278 } 1279 1280 out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf") 1281 1282 actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1) 1283 if actual != "nameserver 127.0.0.1 options ndots:3" { 1284 c.Fatalf("expected 'nameserver 127.0.0.1 options ndots:3', but says: %q", actual) 1285 } 1286 } 1287 1288 func (s *DockerSuite) TestRunDnsRepeatOptions(c *check.C) { 1289 testRequires(c, DaemonIsLinux) 1290 out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf") 1291 1292 actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1) 1293 if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" { 1294 c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual) 1295 } 1296 } 1297 1298 func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { 1299 // Not applicable on Windows as testing Unix specific functionality 1300 testRequires(c, SameHostDaemon, DaemonIsLinux) 1301 1302 origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") 1303 if os.IsNotExist(err) { 1304 c.Fatalf("/etc/resolv.conf does not exist") 1305 } 1306 1307 hostNamservers := resolvconf.GetNameservers(origResolvConf, netutils.IP) 1308 hostSearch := resolvconf.GetSearchDomains(origResolvConf) 1309 1310 var out string 1311 out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf") 1312 1313 if actualNameservers := resolvconf.GetNameservers([]byte(out), netutils.IP); string(actualNameservers[0]) != "127.0.0.1" { 1314 c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0])) 1315 } 1316 1317 actualSearch := resolvconf.GetSearchDomains([]byte(out)) 1318 if len(actualSearch) != len(hostSearch) { 1319 c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) 1320 } 1321 for i := range actualSearch { 1322 if actualSearch[i] != hostSearch[i] { 1323 c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) 1324 } 1325 } 1326 1327 out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") 1328 1329 actualNameservers := resolvconf.GetNameservers([]byte(out), netutils.IP) 1330 if len(actualNameservers) != len(hostNamservers) { 1331 c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers)) 1332 } 1333 for i := range actualNameservers { 1334 if actualNameservers[i] != hostNamservers[i] { 1335 c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i]) 1336 } 1337 } 1338 1339 if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" { 1340 c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0])) 1341 } 1342 1343 // test with file 1344 tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1") 1345 if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { 1346 c.Fatal(err) 1347 } 1348 // put the old resolvconf back 1349 defer func() { 1350 if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil { 1351 c.Fatal(err) 1352 } 1353 }() 1354 1355 resolvConf, err := ioutil.ReadFile("/etc/resolv.conf") 1356 if os.IsNotExist(err) { 1357 c.Fatalf("/etc/resolv.conf does not exist") 1358 } 1359 1360 hostNamservers = resolvconf.GetNameservers(resolvConf, netutils.IP) 1361 hostSearch = resolvconf.GetSearchDomains(resolvConf) 1362 1363 out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") 1364 if actualNameservers = resolvconf.GetNameservers([]byte(out), netutils.IP); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 { 1365 c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers) 1366 } 1367 1368 actualSearch = resolvconf.GetSearchDomains([]byte(out)) 1369 if len(actualSearch) != len(hostSearch) { 1370 c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) 1371 } 1372 for i := range actualSearch { 1373 if actualSearch[i] != hostSearch[i] { 1374 c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) 1375 } 1376 } 1377 } 1378 1379 // Test to see if a non-root user can resolve a DNS name. Also 1380 // check if the container resolv.conf file has at least 0644 perm. 1381 func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { 1382 // Not applicable on Windows as Windows does not support --user 1383 testRequires(c, SameHostDaemon, Network, DaemonIsLinux, NotArm) 1384 1385 dockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "apt.dockerproject.org") 1386 1387 cID, err := getIDByName("testperm") 1388 if err != nil { 1389 c.Fatal(err) 1390 } 1391 1392 fmode := (os.FileMode)(0644) 1393 finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf")) 1394 if err != nil { 1395 c.Fatal(err) 1396 } 1397 1398 if (finfo.Mode() & fmode) != fmode { 1399 c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String()) 1400 } 1401 } 1402 1403 // Test if container resolv.conf gets updated the next time it restarts 1404 // if host /etc/resolv.conf has changed. This only applies if the container 1405 // uses the host's /etc/resolv.conf and does not have any dns options provided. 1406 func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) { 1407 // Not applicable on Windows as testing unix specific functionality 1408 testRequires(c, SameHostDaemon, DaemonIsLinux) 1409 1410 tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n") 1411 tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1") 1412 1413 //take a copy of resolv.conf for restoring after test completes 1414 resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf") 1415 if err != nil { 1416 c.Fatal(err) 1417 } 1418 1419 // This test case is meant to test monitoring resolv.conf when it is 1420 // a regular file not a bind mounc. So we unmount resolv.conf and replace 1421 // it with a file containing the original settings. 1422 cmd := exec.Command("umount", "/etc/resolv.conf") 1423 if _, err = runCommand(cmd); err != nil { 1424 c.Fatal(err) 1425 } 1426 1427 //cleanup 1428 defer func() { 1429 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1430 c.Fatal(err) 1431 } 1432 }() 1433 1434 //1. test that a restarting container gets an updated resolv.conf 1435 dockerCmd(c, "run", "--name='first'", "busybox", "true") 1436 containerID1, err := getIDByName("first") 1437 if err != nil { 1438 c.Fatal(err) 1439 } 1440 1441 // replace resolv.conf with our temporary copy 1442 bytesResolvConf := []byte(tmpResolvConf) 1443 if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { 1444 c.Fatal(err) 1445 } 1446 1447 // start the container again to pickup changes 1448 dockerCmd(c, "start", "first") 1449 1450 // check for update in container 1451 containerResolv, err := readContainerFile(containerID1, "resolv.conf") 1452 if err != nil { 1453 c.Fatal(err) 1454 } 1455 if !bytes.Equal(containerResolv, bytesResolvConf) { 1456 c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv)) 1457 } 1458 1459 /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) 1460 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1461 c.Fatal(err) 1462 } */ 1463 //2. test that a restarting container does not receive resolv.conf updates 1464 // if it modified the container copy of the starting point resolv.conf 1465 dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") 1466 containerID2, err := getIDByName("second") 1467 if err != nil { 1468 c.Fatal(err) 1469 } 1470 1471 //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) 1472 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1473 c.Fatal(err) 1474 } 1475 1476 // start the container again 1477 dockerCmd(c, "start", "second") 1478 1479 // check for update in container 1480 containerResolv, err = readContainerFile(containerID2, "resolv.conf") 1481 if err != nil { 1482 c.Fatal(err) 1483 } 1484 1485 if bytes.Equal(containerResolv, resolvConfSystem) { 1486 c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv)) 1487 } 1488 1489 //3. test that a running container's resolv.conf is not modified while running 1490 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 1491 runningContainerID := strings.TrimSpace(out) 1492 1493 // replace resolv.conf 1494 if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { 1495 c.Fatal(err) 1496 } 1497 1498 // check for update in container 1499 containerResolv, err = readContainerFile(runningContainerID, "resolv.conf") 1500 if err != nil { 1501 c.Fatal(err) 1502 } 1503 1504 if bytes.Equal(containerResolv, bytesResolvConf) { 1505 c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv)) 1506 } 1507 1508 //4. test that a running container's resolv.conf is updated upon restart 1509 // (the above container is still running..) 1510 dockerCmd(c, "restart", runningContainerID) 1511 1512 // check for update in container 1513 containerResolv, err = readContainerFile(runningContainerID, "resolv.conf") 1514 if err != nil { 1515 c.Fatal(err) 1516 } 1517 if !bytes.Equal(containerResolv, bytesResolvConf) { 1518 c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv)) 1519 } 1520 1521 //5. test that additions of a localhost resolver are cleaned from 1522 // host resolv.conf before updating container's resolv.conf copies 1523 1524 // replace resolv.conf with a localhost-only nameserver copy 1525 bytesResolvConf = []byte(tmpLocalhostResolvConf) 1526 if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { 1527 c.Fatal(err) 1528 } 1529 1530 // start the container again to pickup changes 1531 dockerCmd(c, "start", "first") 1532 1533 // our first exited container ID should have been updated, but with default DNS 1534 // after the cleanup of resolv.conf found only a localhost nameserver: 1535 containerResolv, err = readContainerFile(containerID1, "resolv.conf") 1536 if err != nil { 1537 c.Fatal(err) 1538 } 1539 1540 expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n" 1541 if !bytes.Equal(containerResolv, []byte(expected)) { 1542 c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv)) 1543 } 1544 1545 //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update 1546 // of containers' resolv.conf. 1547 1548 // Restore the original resolv.conf 1549 if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { 1550 c.Fatal(err) 1551 } 1552 1553 // Run the container so it picks up the old settings 1554 dockerCmd(c, "run", "--name='third'", "busybox", "true") 1555 containerID3, err := getIDByName("third") 1556 if err != nil { 1557 c.Fatal(err) 1558 } 1559 1560 // Create a modified resolv.conf.aside and override resolv.conf with it 1561 bytesResolvConf = []byte(tmpResolvConf) 1562 if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil { 1563 c.Fatal(err) 1564 } 1565 1566 err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf") 1567 if err != nil { 1568 c.Fatal(err) 1569 } 1570 1571 // start the container again to pickup changes 1572 dockerCmd(c, "start", "third") 1573 1574 // check for update in container 1575 containerResolv, err = readContainerFile(containerID3, "resolv.conf") 1576 if err != nil { 1577 c.Fatal(err) 1578 } 1579 if !bytes.Equal(containerResolv, bytesResolvConf) { 1580 c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv)) 1581 } 1582 1583 //cleanup, restore original resolv.conf happens in defer func() 1584 } 1585 1586 func (s *DockerSuite) TestRunAddHost(c *check.C) { 1587 // Not applicable on Windows as it does not support --add-host 1588 testRequires(c, DaemonIsLinux) 1589 out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts") 1590 1591 actual := strings.Trim(out, "\r\n") 1592 if actual != "86.75.30.9\textra" { 1593 c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual) 1594 } 1595 } 1596 1597 // Regression test for #6983 1598 func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) { 1599 _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true") 1600 if exitCode != 0 { 1601 c.Fatalf("Container should have exited with error code 0") 1602 } 1603 } 1604 1605 // Regression test for #6983 1606 func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) { 1607 _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true") 1608 if exitCode != 0 { 1609 c.Fatalf("Container should have exited with error code 0") 1610 } 1611 } 1612 1613 // Regression test for #6983 1614 func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) { 1615 _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true") 1616 if exitCode != 0 { 1617 c.Fatalf("Container should have exited with error code 0") 1618 } 1619 } 1620 1621 // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode 1622 // but using --attach instead of -a to make sure we read the flag correctly 1623 func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) { 1624 cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true") 1625 _, stderr, _, err := runCommandWithStdoutStderr(cmd) 1626 if err == nil { 1627 c.Fatal("Container should have exited with error code different than 0") 1628 } else if !strings.Contains(stderr, "Conflicting options: -a and -d") { 1629 c.Fatal("Should have been returned an error with conflicting options -a and -d") 1630 } 1631 } 1632 1633 func (s *DockerSuite) TestRunState(c *check.C) { 1634 // TODO Windows: This needs some rework as Windows busybox does not support top 1635 testRequires(c, DaemonIsLinux) 1636 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 1637 1638 id := strings.TrimSpace(out) 1639 state := inspectField(c, id, "State.Running") 1640 if state != "true" { 1641 c.Fatal("Container state is 'not running'") 1642 } 1643 pid1 := inspectField(c, id, "State.Pid") 1644 if pid1 == "0" { 1645 c.Fatal("Container state Pid 0") 1646 } 1647 1648 dockerCmd(c, "stop", id) 1649 state = inspectField(c, id, "State.Running") 1650 if state != "false" { 1651 c.Fatal("Container state is 'running'") 1652 } 1653 pid2 := inspectField(c, id, "State.Pid") 1654 if pid2 == pid1 { 1655 c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) 1656 } 1657 1658 dockerCmd(c, "start", id) 1659 state = inspectField(c, id, "State.Running") 1660 if state != "true" { 1661 c.Fatal("Container state is 'not running'") 1662 } 1663 pid3 := inspectField(c, id, "State.Pid") 1664 if pid3 == pid1 { 1665 c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) 1666 } 1667 } 1668 1669 // Test for #1737 1670 func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) { 1671 // Not applicable on Windows as it does not support uid or gid in this way 1672 testRequires(c, DaemonIsLinux) 1673 name := "testrunvolumesuidgid" 1674 _, err := buildImage(name, 1675 `FROM busybox 1676 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 1677 RUN echo 'dockerio:x:1001:' >> /etc/group 1678 RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`, 1679 true) 1680 if err != nil { 1681 c.Fatal(err) 1682 } 1683 1684 // Test that the uid and gid is copied from the image to the volume 1685 out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'") 1686 out = strings.TrimSpace(out) 1687 if out != "dockerio:dockerio" { 1688 c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out) 1689 } 1690 } 1691 1692 // Test for #1582 1693 func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) { 1694 // TODO Windows, post TP4. Windows does not yet support volume functionality 1695 // that copies from the image to the volume. 1696 testRequires(c, DaemonIsLinux) 1697 name := "testruncopyvolumecontent" 1698 _, err := buildImage(name, 1699 `FROM busybox 1700 RUN mkdir -p /hello/local && echo hello > /hello/local/world`, 1701 true) 1702 if err != nil { 1703 c.Fatal(err) 1704 } 1705 1706 // Test that the content is copied from the image to the volume 1707 out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello") 1708 if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) { 1709 c.Fatal("Container failed to transfer content to volume") 1710 } 1711 } 1712 1713 func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) { 1714 name := "testrunmdcleanuponentrypoint" 1715 if _, err := buildImage(name, 1716 `FROM busybox 1717 ENTRYPOINT ["echo"] 1718 CMD ["testingpoint"]`, 1719 true); err != nil { 1720 c.Fatal(err) 1721 } 1722 1723 out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name) 1724 if exit != 0 { 1725 c.Fatalf("expected exit code 0 received %d, out: %q", exit, out) 1726 } 1727 out = strings.TrimSpace(out) 1728 expected := "root" 1729 if daemonPlatform == "windows" { 1730 // TODO Windows: Remove this check once TP4 is no longer supported. 1731 if windowsDaemonKV < 14250 { 1732 expected = `nt authority\system` 1733 } else { 1734 expected = `user manager\containeradministrator` 1735 } 1736 } 1737 if out != expected { 1738 c.Fatalf("Expected output %s, got %q", expected, out) 1739 } 1740 } 1741 1742 // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected 1743 func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) { 1744 existingFile := "/bin/cat" 1745 expected := "not a directory" 1746 if daemonPlatform == "windows" { 1747 existingFile = `\windows\system32\ntdll.dll` 1748 expected = `Cannot mkdir: \windows\system32\ntdll.dll is not a directory.` 1749 } 1750 1751 out, exitCode, err := dockerCmdWithError("run", "-w", existingFile, "busybox") 1752 if !(err != nil && exitCode == 125 && strings.Contains(out, expected)) { 1753 c.Fatalf("Existing binary as a directory should error out with exitCode 125; we got: %s, exitCode: %d", out, exitCode) 1754 } 1755 } 1756 1757 func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) { 1758 name := "testrunexitonstdinclose" 1759 1760 meow := "/bin/cat" 1761 delay := 1 1762 if daemonPlatform == "windows" { 1763 meow = "cat" 1764 delay = 60 1765 } 1766 runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow) 1767 1768 stdin, err := runCmd.StdinPipe() 1769 if err != nil { 1770 c.Fatal(err) 1771 } 1772 stdout, err := runCmd.StdoutPipe() 1773 if err != nil { 1774 c.Fatal(err) 1775 } 1776 1777 if err := runCmd.Start(); err != nil { 1778 c.Fatal(err) 1779 } 1780 if _, err := stdin.Write([]byte("hello\n")); err != nil { 1781 c.Fatal(err) 1782 } 1783 1784 r := bufio.NewReader(stdout) 1785 line, err := r.ReadString('\n') 1786 if err != nil { 1787 c.Fatal(err) 1788 } 1789 line = strings.TrimSpace(line) 1790 if line != "hello" { 1791 c.Fatalf("Output should be 'hello', got '%q'", line) 1792 } 1793 if err := stdin.Close(); err != nil { 1794 c.Fatal(err) 1795 } 1796 finish := make(chan error) 1797 go func() { 1798 finish <- runCmd.Wait() 1799 close(finish) 1800 }() 1801 select { 1802 case err := <-finish: 1803 c.Assert(err, check.IsNil) 1804 case <-time.After(time.Duration(delay) * time.Second): 1805 c.Fatal("docker run failed to exit on stdin close") 1806 } 1807 state := inspectField(c, name, "State.Running") 1808 1809 if state != "false" { 1810 c.Fatal("Container must be stopped after stdin closing") 1811 } 1812 } 1813 1814 // Test for #2267 1815 func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) { 1816 // Cannot run on Windows as Windows does not support diff. 1817 testRequires(c, DaemonIsLinux) 1818 name := "writehosts" 1819 out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts") 1820 if !strings.Contains(out, "test2267") { 1821 c.Fatal("/etc/hosts should contain 'test2267'") 1822 } 1823 1824 out, _ = dockerCmd(c, "diff", name) 1825 if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { 1826 c.Fatal("diff should be empty") 1827 } 1828 } 1829 1830 func eqToBaseDiff(out string, c *check.C) bool { 1831 name := "eqToBaseDiff" + stringutils.GenerateRandomAlphaOnlyString(32) 1832 dockerCmd(c, "run", "--name", name, "busybox", "echo", "hello") 1833 cID, err := getIDByName(name) 1834 c.Assert(err, check.IsNil) 1835 1836 baseDiff, _ := dockerCmd(c, "diff", cID) 1837 baseArr := strings.Split(baseDiff, "\n") 1838 sort.Strings(baseArr) 1839 outArr := strings.Split(out, "\n") 1840 sort.Strings(outArr) 1841 return sliceEq(baseArr, outArr) 1842 } 1843 1844 func sliceEq(a, b []string) bool { 1845 if len(a) != len(b) { 1846 return false 1847 } 1848 1849 for i := range a { 1850 if a[i] != b[i] { 1851 return false 1852 } 1853 } 1854 1855 return true 1856 } 1857 1858 // Test for #2267 1859 func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) { 1860 // Cannot run on Windows as Windows does not support diff. 1861 testRequires(c, DaemonIsLinux) 1862 name := "writehostname" 1863 out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname") 1864 if !strings.Contains(out, "test2267") { 1865 c.Fatal("/etc/hostname should contain 'test2267'") 1866 } 1867 1868 out, _ = dockerCmd(c, "diff", name) 1869 if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { 1870 c.Fatal("diff should be empty") 1871 } 1872 } 1873 1874 // Test for #2267 1875 func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) { 1876 // Cannot run on Windows as Windows does not support diff. 1877 testRequires(c, DaemonIsLinux) 1878 name := "writeresolv" 1879 out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf") 1880 if !strings.Contains(out, "test2267") { 1881 c.Fatal("/etc/resolv.conf should contain 'test2267'") 1882 } 1883 1884 out, _ = dockerCmd(c, "diff", name) 1885 if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { 1886 c.Fatal("diff should be empty") 1887 } 1888 } 1889 1890 func (s *DockerSuite) TestRunWithBadDevice(c *check.C) { 1891 // Cannot run on Windows as Windows does not support --device 1892 testRequires(c, DaemonIsLinux) 1893 name := "baddevice" 1894 out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true") 1895 1896 if err == nil { 1897 c.Fatal("Run should fail with bad device") 1898 } 1899 expected := `"/etc": not a device node` 1900 if !strings.Contains(out, expected) { 1901 c.Fatalf("Output should contain %q, actual out: %q", expected, out) 1902 } 1903 } 1904 1905 func (s *DockerSuite) TestRunEntrypoint(c *check.C) { 1906 name := "entrypoint" 1907 1908 // Note Windows does not have an echo.exe built in. 1909 var out, expected string 1910 if daemonPlatform == "windows" { 1911 out, _ = dockerCmd(c, "run", "--name", name, "--entrypoint", "cmd /s /c echo", "busybox", "foobar") 1912 expected = "foobar\r\n" 1913 } else { 1914 out, _ = dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar") 1915 expected = "foobar" 1916 } 1917 1918 if out != expected { 1919 c.Fatalf("Output should be %q, actual out: %q", expected, out) 1920 } 1921 } 1922 1923 func (s *DockerSuite) TestRunBindMounts(c *check.C) { 1924 testRequires(c, SameHostDaemon) 1925 if daemonPlatform == "linux" { 1926 testRequires(c, DaemonIsLinux, NotUserNamespace) 1927 } 1928 1929 tmpDir, err := ioutil.TempDir("", "docker-test-container") 1930 if err != nil { 1931 c.Fatal(err) 1932 } 1933 1934 defer os.RemoveAll(tmpDir) 1935 writeFile(path.Join(tmpDir, "touch-me"), "", c) 1936 1937 // TODO Windows Post TP4. Windows does not yet support :ro binds 1938 if daemonPlatform != "windows" { 1939 // Test reading from a read-only bind mount 1940 out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp") 1941 if !strings.Contains(out, "touch-me") { 1942 c.Fatal("Container failed to read from bind mount") 1943 } 1944 } 1945 1946 // test writing to bind mount 1947 if daemonPlatform == "windows" { 1948 dockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla") 1949 } else { 1950 dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") 1951 } 1952 1953 readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist 1954 1955 // test mounting to an illegal destination directory 1956 _, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".") 1957 if err == nil { 1958 c.Fatal("Container bind mounted illegal directory") 1959 } 1960 1961 // Windows does not (and likely never will) support mounting a single file 1962 if daemonPlatform != "windows" { 1963 // test mount a file 1964 dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") 1965 content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist 1966 expected := "yotta" 1967 if content != expected { 1968 c.Fatalf("Output should be %q, actual out: %q", expected, content) 1969 } 1970 } 1971 } 1972 1973 // Ensure that CIDFile gets deleted if it's empty 1974 // Perform this test by making `docker run` fail 1975 func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) { 1976 tmpDir, err := ioutil.TempDir("", "TestRunCidFile") 1977 if err != nil { 1978 c.Fatal(err) 1979 } 1980 defer os.RemoveAll(tmpDir) 1981 tmpCidFile := path.Join(tmpDir, "cid") 1982 1983 image := "emptyfs" 1984 if daemonPlatform == "windows" { 1985 // Windows can't support an emptyfs image. Just use the regular Windows image 1986 image = WindowsBaseImage 1987 } 1988 out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image) 1989 if err == nil { 1990 c.Fatalf("Run without command must fail. out=%s", out) 1991 } else if !strings.Contains(out, "No command specified") { 1992 c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err) 1993 } 1994 1995 if _, err := os.Stat(tmpCidFile); err == nil { 1996 c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile) 1997 } 1998 } 1999 2000 // #2098 - Docker cidFiles only contain short version of the containerId 2001 //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test" 2002 // TestRunCidFile tests that run --cidfile returns the longid 2003 func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) { 2004 tmpDir, err := ioutil.TempDir("", "TestRunCidFile") 2005 if err != nil { 2006 c.Fatal(err) 2007 } 2008 tmpCidFile := path.Join(tmpDir, "cid") 2009 defer os.RemoveAll(tmpDir) 2010 2011 out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true") 2012 2013 id := strings.TrimSpace(out) 2014 buffer, err := ioutil.ReadFile(tmpCidFile) 2015 if err != nil { 2016 c.Fatal(err) 2017 } 2018 cid := string(buffer) 2019 if len(cid) != 64 { 2020 c.Fatalf("--cidfile should be a long id, not %q", id) 2021 } 2022 if cid != id { 2023 c.Fatalf("cid must be equal to %s, got %s", id, cid) 2024 } 2025 } 2026 2027 func (s *DockerSuite) TestRunSetMacAddress(c *check.C) { 2028 mac := "12:34:56:78:9a:bc" 2029 var out string 2030 if daemonPlatform == "windows" { 2031 out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'") 2032 mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs 2033 } else { 2034 out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'") 2035 } 2036 2037 actualMac := strings.TrimSpace(out) 2038 if actualMac != mac { 2039 c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac) 2040 } 2041 } 2042 2043 func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) { 2044 // TODO Windows. Network settings are not propagated back to inspect. 2045 testRequires(c, DaemonIsLinux) 2046 mac := "12:34:56:78:9a:bc" 2047 out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top") 2048 2049 id := strings.TrimSpace(out) 2050 inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress") 2051 if inspectedMac != mac { 2052 c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac) 2053 } 2054 } 2055 2056 // test docker run use an invalid mac address 2057 func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) { 2058 out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox") 2059 //use an invalid mac address should with an error out 2060 if err == nil || !strings.Contains(out, "is not a valid mac address") { 2061 c.Fatalf("run with an invalid --mac-address should with error out") 2062 } 2063 } 2064 2065 func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) { 2066 // TODO Windows. Network settings are not propagated back to inspect. 2067 testRequires(c, SameHostDaemon, DaemonIsLinux) 2068 2069 out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top") 2070 2071 id := strings.TrimSpace(out) 2072 ip := inspectField(c, id, "NetworkSettings.Networks.bridge.IPAddress") 2073 iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip), 2074 "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT") 2075 out, _, err := runCommandWithOutput(iptCmd) 2076 if err != nil { 2077 c.Fatal(err, out) 2078 } 2079 if err := deleteContainer(id); err != nil { 2080 c.Fatal(err) 2081 } 2082 2083 dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top") 2084 } 2085 2086 func (s *DockerSuite) TestRunPortInUse(c *check.C) { 2087 // TODO Windows. The duplicate NAT message returned by Windows will be 2088 // changing as is currently completely undecipherable. Does need modifying 2089 // to run sh rather than top though as top isn't in Windows busybox. 2090 testRequires(c, SameHostDaemon, DaemonIsLinux) 2091 2092 port := "1234" 2093 dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") 2094 2095 out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top") 2096 if err == nil { 2097 c.Fatalf("Binding on used port must fail") 2098 } 2099 if !strings.Contains(out, "port is already allocated") { 2100 c.Fatalf("Out must be about \"port is already allocated\", got %s", out) 2101 } 2102 } 2103 2104 // https://github.com/docker/docker/issues/12148 2105 func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) { 2106 // TODO Windows. -P is not yet supported 2107 testRequires(c, DaemonIsLinux) 2108 // allocate a dynamic port to get the most recent 2109 out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top") 2110 2111 id := strings.TrimSpace(out) 2112 out, _ = dockerCmd(c, "port", id, "80") 2113 2114 strPort := strings.Split(strings.TrimSpace(out), ":")[1] 2115 port, err := strconv.ParseInt(strPort, 10, 64) 2116 if err != nil { 2117 c.Fatalf("invalid port, got: %s, error: %s", strPort, err) 2118 } 2119 2120 // allocate a static port and a dynamic port together, with static port 2121 // takes the next recent port in dynamic port range. 2122 dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top") 2123 } 2124 2125 // Regression test for #7792 2126 func (s *DockerSuite) TestRunMountOrdering(c *check.C) { 2127 // TODO Windows: Post TP4. Updated, but Windows does not support nested mounts currently. 2128 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2129 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2130 2131 tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test") 2132 if err != nil { 2133 c.Fatal(err) 2134 } 2135 defer os.RemoveAll(tmpDir) 2136 2137 tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2") 2138 if err != nil { 2139 c.Fatal(err) 2140 } 2141 defer os.RemoveAll(tmpDir2) 2142 2143 // Create a temporary tmpfs mounc. 2144 fooDir := filepath.Join(tmpDir, "foo") 2145 if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil { 2146 c.Fatalf("failed to mkdir at %s - %s", fooDir, err) 2147 } 2148 2149 if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil { 2150 c.Fatal(err) 2151 } 2152 2153 if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil { 2154 c.Fatal(err) 2155 } 2156 2157 if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil { 2158 c.Fatal(err) 2159 } 2160 2161 dockerCmd(c, "run", 2162 "-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir), 2163 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir), 2164 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2), 2165 "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2/foo", fooDir), 2166 "busybox:latest", "sh", "-c", 2167 "ls "+prefix+"/tmp/touch-me && ls "+prefix+"/tmp/foo/touch-me && ls "+prefix+"/tmp/tmp2/touch-me && ls "+prefix+"/tmp/tmp2/foo/touch-me") 2168 } 2169 2170 // Regression test for https://github.com/docker/docker/issues/8259 2171 func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) { 2172 // Not applicable on Windows as Windows does not support volumes 2173 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2174 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2175 2176 tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink") 2177 if err != nil { 2178 c.Fatal(err) 2179 } 2180 defer os.RemoveAll(tmpDir) 2181 2182 linkPath := os.TempDir() + "/testlink2" 2183 if err := os.Symlink(tmpDir, linkPath); err != nil { 2184 c.Fatal(err) 2185 } 2186 defer os.RemoveAll(linkPath) 2187 2188 // Create first container 2189 dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") 2190 2191 // Create second container with same symlinked path 2192 // This will fail if the referenced issue is hit with a "Volume exists" error 2193 dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") 2194 } 2195 2196 //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container 2197 func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) { 2198 // While Windows supports volumes, it does not support --add-host hence 2199 // this test is not applicable on Windows. 2200 testRequires(c, DaemonIsLinux) 2201 out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf") 2202 if !strings.Contains(out, "nameserver 127.0.0.1") { 2203 c.Fatal("/etc volume mount hides /etc/resolv.conf") 2204 } 2205 2206 out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname") 2207 if !strings.Contains(out, "test123") { 2208 c.Fatal("/etc volume mount hides /etc/hostname") 2209 } 2210 2211 out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts") 2212 out = strings.Replace(out, "\n", " ", -1) 2213 if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") { 2214 c.Fatal("/etc volume mount hides /etc/hosts") 2215 } 2216 } 2217 2218 func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) { 2219 // TODO Windows (Post TP4). Windows does not support volumes which 2220 // are pre-populated such as is built in the dockerfile used in this test. 2221 testRequires(c, DaemonIsLinux) 2222 if _, err := buildImage("dataimage", 2223 `FROM busybox 2224 RUN mkdir -p /foo 2225 RUN touch /foo/bar`, 2226 true); err != nil { 2227 c.Fatal(err) 2228 } 2229 2230 dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox") 2231 2232 if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { 2233 c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out) 2234 } 2235 2236 tmpDir := randomTmpDirPath("docker_test_bind_mount_copy_data", daemonPlatform) 2237 if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { 2238 c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out) 2239 } 2240 } 2241 2242 func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) { 2243 // just run with unknown image 2244 cmd := exec.Command(dockerBinary, "run", "asdfsg") 2245 stdout := bytes.NewBuffer(nil) 2246 cmd.Stdout = stdout 2247 if err := cmd.Run(); err == nil { 2248 c.Fatal("Run with unknown image should fail") 2249 } 2250 if stdout.Len() != 0 { 2251 c.Fatalf("Stdout contains output from pull: %s", stdout) 2252 } 2253 } 2254 2255 func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) { 2256 testRequires(c, SameHostDaemon) 2257 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 2258 if _, err := buildImage("run_volumes_clean_paths", 2259 `FROM busybox 2260 VOLUME `+prefix+`/foo/`, 2261 true); err != nil { 2262 c.Fatal(err) 2263 } 2264 2265 dockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths") 2266 2267 out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash) 2268 if err != errMountNotFound { 2269 c.Fatalf("Found unexpected volume entry for '%s/foo/' in volumes\n%q", prefix, out) 2270 } 2271 2272 out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`) 2273 c.Assert(err, check.IsNil) 2274 if !strings.Contains(strings.ToLower(out), strings.ToLower(volumesConfigPath)) { 2275 c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out) 2276 } 2277 2278 out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar"+slash) 2279 if err != errMountNotFound { 2280 c.Fatalf("Found unexpected volume entry for '%s/bar/' in volumes\n%q", prefix, out) 2281 } 2282 2283 out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar") 2284 c.Assert(err, check.IsNil) 2285 if !strings.Contains(strings.ToLower(out), strings.ToLower(volumesConfigPath)) { 2286 c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out) 2287 } 2288 } 2289 2290 // Regression test for #3631 2291 func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) { 2292 // TODO Windows: This should be able to run on Windows if can find an 2293 // alternate to /dev/zero and /dev/stdout. 2294 testRequires(c, DaemonIsLinux) 2295 cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv") 2296 2297 stdout, err := cont.StdoutPipe() 2298 if err != nil { 2299 c.Fatal(err) 2300 } 2301 2302 if err := cont.Start(); err != nil { 2303 c.Fatal(err) 2304 } 2305 n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil) 2306 if err != nil { 2307 c.Fatal(err) 2308 } 2309 2310 expected := 2 * 1024 * 2000 2311 if n != expected { 2312 c.Fatalf("Expected %d, got %d", expected, n) 2313 } 2314 } 2315 2316 func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) { 2317 // TODO Windows: -P is not currently supported. Also network 2318 // settings are not propagated back. 2319 testRequires(c, DaemonIsLinux) 2320 out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top") 2321 2322 id := strings.TrimSpace(out) 2323 portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") 2324 var ports nat.PortMap 2325 if err := unmarshalJSON([]byte(portstr), &ports); err != nil { 2326 c.Fatal(err) 2327 } 2328 for port, binding := range ports { 2329 portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) 2330 if portnum < 3000 || portnum > 3003 { 2331 c.Fatalf("Port %d is out of range ", portnum) 2332 } 2333 if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { 2334 c.Fatalf("Port is not mapped for the port %s", port) 2335 } 2336 } 2337 } 2338 2339 func (s *DockerSuite) TestRunExposePort(c *check.C) { 2340 out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox") 2341 c.Assert(err, checker.NotNil, check.Commentf("--expose with an invalid port should error out")) 2342 c.Assert(out, checker.Contains, "invalid range format for --expose") 2343 } 2344 2345 func (s *DockerSuite) TestRunUnknownCommand(c *check.C) { 2346 out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada") 2347 2348 cID := strings.TrimSpace(out) 2349 _, _, err := dockerCmdWithError("start", cID) 2350 2351 // Windows and Linux are different here by architectural design. Linux will 2352 // fail to start the container, so an error is expected. Windows will 2353 // successfully start the container, and once started attempt to execute 2354 // the command which will fail. 2355 if daemonPlatform == "windows" { 2356 // Wait for it to exit. 2357 waitExited(cID, 30*time.Second) 2358 c.Assert(err, check.IsNil) 2359 } else { 2360 c.Assert(err, check.NotNil) 2361 } 2362 2363 rc := inspectField(c, cID, "State.ExitCode") 2364 if rc == "0" { 2365 c.Fatalf("ExitCode(%v) cannot be 0", rc) 2366 } 2367 } 2368 2369 func (s *DockerSuite) TestRunModeIpcHost(c *check.C) { 2370 // Not applicable on Windows as uses Unix-specific capabilities 2371 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2372 2373 hostIpc, err := os.Readlink("/proc/1/ns/ipc") 2374 if err != nil { 2375 c.Fatal(err) 2376 } 2377 2378 out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc") 2379 out = strings.Trim(out, "\n") 2380 if hostIpc != out { 2381 c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out) 2382 } 2383 2384 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc") 2385 out = strings.Trim(out, "\n") 2386 if hostIpc == out { 2387 c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out) 2388 } 2389 } 2390 2391 func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) { 2392 // Not applicable on Windows as uses Unix-specific capabilities 2393 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2394 2395 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") 2396 2397 id := strings.TrimSpace(out) 2398 state := inspectField(c, id, "State.Running") 2399 if state != "true" { 2400 c.Fatal("Container state is 'not running'") 2401 } 2402 pid1 := inspectField(c, id, "State.Pid") 2403 2404 parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1)) 2405 if err != nil { 2406 c.Fatal(err) 2407 } 2408 2409 out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc") 2410 out = strings.Trim(out, "\n") 2411 if parentContainerIpc != out { 2412 c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out) 2413 } 2414 2415 catOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "cat", "/dev/shm/test") 2416 if catOutput != "test" { 2417 c.Fatalf("Output of /dev/shm/test expected test but found: %s", catOutput) 2418 } 2419 2420 // check that /dev/mqueue is actually of mqueue type 2421 grepOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "grep", "/dev/mqueue", "/proc/mounts") 2422 if !strings.HasPrefix(grepOutput, "mqueue /dev/mqueue mqueue rw") { 2423 c.Fatalf("Output of 'grep /proc/mounts' expected 'mqueue /dev/mqueue mqueue rw' but found: %s", grepOutput) 2424 } 2425 2426 lsOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "ls", "/dev/mqueue") 2427 lsOutput = strings.Trim(lsOutput, "\n") 2428 if lsOutput != "toto" { 2429 c.Fatalf("Output of 'ls /dev/mqueue' expected 'toto' but found: %s", lsOutput) 2430 } 2431 } 2432 2433 func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) { 2434 // Not applicable on Windows as uses Unix-specific capabilities 2435 testRequires(c, DaemonIsLinux, NotUserNamespace) 2436 out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top") 2437 if !strings.Contains(out, "abcd1234") || err == nil { 2438 c.Fatalf("run IPC from a non exists container should with correct error out") 2439 } 2440 } 2441 2442 func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) { 2443 // Not applicable on Windows as uses Unix-specific capabilities 2444 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2445 2446 out, _ := dockerCmd(c, "create", "busybox") 2447 2448 id := strings.TrimSpace(out) 2449 out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox") 2450 if err == nil { 2451 c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err) 2452 } 2453 } 2454 2455 func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) { 2456 // Not applicable on Windows as uses Unix-specific capabilities 2457 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2458 2459 dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") 2460 defer os.Remove("/dev/mqueue/toto") 2461 defer os.Remove("/dev/shm/test") 2462 volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm") 2463 c.Assert(err, checker.IsNil) 2464 if volPath != "/dev/shm" { 2465 c.Fatalf("volumePath should have been /dev/shm, was %s", volPath) 2466 } 2467 2468 out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test") 2469 if out != "test" { 2470 c.Fatalf("Output of /dev/shm/test expected test but found: %s", out) 2471 } 2472 2473 // Check that the mq was created 2474 if _, err := os.Stat("/dev/mqueue/toto"); err != nil { 2475 c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error()) 2476 } 2477 } 2478 2479 func (s *DockerSuite) TestContainerNetworkMode(c *check.C) { 2480 // Not applicable on Windows as uses Unix-specific capabilities 2481 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2482 2483 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 2484 id := strings.TrimSpace(out) 2485 c.Assert(waitRun(id), check.IsNil) 2486 pid1 := inspectField(c, id, "State.Pid") 2487 2488 parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 2489 if err != nil { 2490 c.Fatal(err) 2491 } 2492 2493 out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net") 2494 out = strings.Trim(out, "\n") 2495 if parentContainerNet != out { 2496 c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out) 2497 } 2498 } 2499 2500 func (s *DockerSuite) TestRunModePidHost(c *check.C) { 2501 // Not applicable on Windows as uses Unix-specific capabilities 2502 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2503 2504 hostPid, err := os.Readlink("/proc/1/ns/pid") 2505 if err != nil { 2506 c.Fatal(err) 2507 } 2508 2509 out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid") 2510 out = strings.Trim(out, "\n") 2511 if hostPid != out { 2512 c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out) 2513 } 2514 2515 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid") 2516 out = strings.Trim(out, "\n") 2517 if hostPid == out { 2518 c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out) 2519 } 2520 } 2521 2522 func (s *DockerSuite) TestRunModeUTSHost(c *check.C) { 2523 // Not applicable on Windows as uses Unix-specific capabilities 2524 testRequires(c, SameHostDaemon, DaemonIsLinux) 2525 2526 hostUTS, err := os.Readlink("/proc/1/ns/uts") 2527 if err != nil { 2528 c.Fatal(err) 2529 } 2530 2531 out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts") 2532 out = strings.Trim(out, "\n") 2533 if hostUTS != out { 2534 c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out) 2535 } 2536 2537 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts") 2538 out = strings.Trim(out, "\n") 2539 if hostUTS == out { 2540 c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out) 2541 } 2542 2543 out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps") 2544 c.Assert(out, checker.Contains, runconfig.ErrConflictUTSHostname.Error()) 2545 } 2546 2547 func (s *DockerSuite) TestRunTLSverify(c *check.C) { 2548 // Remote daemons use TLS and this test is not applicable when TLS is required. 2549 testRequires(c, SameHostDaemon) 2550 if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 { 2551 c.Fatalf("Should have worked: %v:\n%v", err, out) 2552 } 2553 2554 // Regardless of whether we specify true or false we need to 2555 // test to make sure tls is turned on if --tlsverify is specified at all 2556 out, code, err := dockerCmdWithError("--tlsverify=false", "ps") 2557 if err == nil || code == 0 || !strings.Contains(out, "trying to connect") { 2558 c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err) 2559 } 2560 2561 out, code, err = dockerCmdWithError("--tlsverify=true", "ps") 2562 if err == nil || code == 0 || !strings.Contains(out, "cert") { 2563 c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err) 2564 } 2565 } 2566 2567 func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) { 2568 // TODO Windows. Once moved to libnetwork/CNM, this may be able to be 2569 // re-instated. 2570 testRequires(c, DaemonIsLinux) 2571 // first find allocator current position 2572 out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") 2573 2574 id := strings.TrimSpace(out) 2575 out, _ = dockerCmd(c, "port", id) 2576 2577 out = strings.TrimSpace(out) 2578 if out == "" { 2579 c.Fatal("docker port command output is empty") 2580 } 2581 out = strings.Split(out, ":")[1] 2582 lastPort, err := strconv.Atoi(out) 2583 if err != nil { 2584 c.Fatal(err) 2585 } 2586 port := lastPort + 1 2587 l, err := net.Listen("tcp", ":"+strconv.Itoa(port)) 2588 if err != nil { 2589 c.Fatal(err) 2590 } 2591 defer l.Close() 2592 2593 out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") 2594 2595 id = strings.TrimSpace(out) 2596 dockerCmd(c, "port", id) 2597 } 2598 2599 func (s *DockerSuite) TestRunTTYWithPipe(c *check.C) { 2600 errChan := make(chan error) 2601 go func() { 2602 defer close(errChan) 2603 2604 cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true") 2605 if _, err := cmd.StdinPipe(); err != nil { 2606 errChan <- err 2607 return 2608 } 2609 2610 expected := "cannot enable tty mode" 2611 if out, _, err := runCommandWithOutput(cmd); err == nil { 2612 errChan <- fmt.Errorf("run should have failed") 2613 return 2614 } else if !strings.Contains(out, expected) { 2615 errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected) 2616 return 2617 } 2618 }() 2619 2620 select { 2621 case err := <-errChan: 2622 c.Assert(err, check.IsNil) 2623 case <-time.After(6 * time.Second): 2624 c.Fatal("container is running but should have failed") 2625 } 2626 } 2627 2628 func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) { 2629 addr := "00:16:3E:08:00:50" 2630 cmd := "ifconfig" 2631 image := "busybox" 2632 expected := addr 2633 2634 if daemonPlatform == "windows" { 2635 cmd = "ipconfig /all" 2636 image = WindowsBaseImage 2637 expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1) 2638 2639 } 2640 2641 if out, _ := dockerCmd(c, "run", "--mac-address", addr, image, cmd); !strings.Contains(out, expected) { 2642 c.Fatalf("Output should have contained %q: %s", expected, out) 2643 } 2644 } 2645 2646 func (s *DockerSuite) TestRunNetHost(c *check.C) { 2647 // Not applicable on Windows as uses Unix-specific capabilities 2648 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2649 2650 hostNet, err := os.Readlink("/proc/1/ns/net") 2651 if err != nil { 2652 c.Fatal(err) 2653 } 2654 2655 out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net") 2656 out = strings.Trim(out, "\n") 2657 if hostNet != out { 2658 c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out) 2659 } 2660 2661 out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net") 2662 out = strings.Trim(out, "\n") 2663 if hostNet == out { 2664 c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out) 2665 } 2666 } 2667 2668 func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) { 2669 // TODO Windows. As Windows networking evolves and converges towards 2670 // CNM, this test may be possible to enable on Windows. 2671 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2672 2673 dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") 2674 dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") 2675 } 2676 2677 func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) { 2678 // Not applicable on Windows as uses Unix-specific capabilities 2679 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 2680 2681 hostNet, err := os.Readlink("/proc/1/ns/net") 2682 if err != nil { 2683 c.Fatal(err) 2684 } 2685 2686 dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top") 2687 2688 out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net") 2689 out = strings.Trim(out, "\n") 2690 if hostNet != out { 2691 c.Fatalf("Container should have host network namespace") 2692 } 2693 } 2694 2695 func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) { 2696 // TODO Windows. This may be possible to enable in the future. However, 2697 // Windows does not currently support --expose, or populate the network 2698 // settings seen through inspect. 2699 testRequires(c, DaemonIsLinux) 2700 out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top") 2701 2702 id := strings.TrimSpace(out) 2703 portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") 2704 2705 var ports nat.PortMap 2706 err := unmarshalJSON([]byte(portstr), &ports) 2707 c.Assert(err, checker.IsNil, check.Commentf("failed to unmarshal: %v", portstr)) 2708 for port, binding := range ports { 2709 portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) 2710 if portnum < 3000 || portnum > 3003 { 2711 c.Fatalf("Port %d is out of range ", portnum) 2712 } 2713 if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { 2714 c.Fatal("Port is not mapped for the port "+port, out) 2715 } 2716 } 2717 } 2718 2719 func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) { 2720 dockerCmd(c, "run", "-d", "--name", "test", "busybox", "sleep", "30") 2721 out := inspectField(c, "test", "HostConfig.RestartPolicy.Name") 2722 if out != "no" { 2723 c.Fatalf("Set default restart policy failed") 2724 } 2725 } 2726 2727 func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) { 2728 out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") 2729 timeout := 10 * time.Second 2730 if daemonPlatform == "windows" { 2731 timeout = 120 * time.Second 2732 } 2733 2734 id := strings.TrimSpace(string(out)) 2735 if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil { 2736 c.Fatal(err) 2737 } 2738 2739 count := inspectField(c, id, "RestartCount") 2740 if count != "3" { 2741 c.Fatalf("Container was restarted %s times, expected %d", count, 3) 2742 } 2743 2744 MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") 2745 if MaximumRetryCount != "3" { 2746 c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3") 2747 } 2748 } 2749 2750 func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) { 2751 dockerCmd(c, "run", "--rm", "busybox", "touch", "/file") 2752 } 2753 2754 func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) { 2755 // Not applicable on Windows which does not support --read-only 2756 testRequires(c, DaemonIsLinux) 2757 2758 testReadOnlyFile(c, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me") 2759 } 2760 2761 func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) { 2762 // Not applicable on Windows due to use of Unix specific functionality, plus 2763 // the use of --read-only which is not supported. 2764 // --read-only + userns has remount issues 2765 testRequires(c, DaemonIsLinux, NotUserNamespace) 2766 2767 // Ensure we have not broken writing /dev/pts 2768 out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount") 2769 if status != 0 { 2770 c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.") 2771 } 2772 expected := "type devpts (rw," 2773 if !strings.Contains(string(out), expected) { 2774 c.Fatalf("expected output to contain %s but contains %s", expected, out) 2775 } 2776 } 2777 2778 func testReadOnlyFile(c *check.C, filenames ...string) { 2779 // Not applicable on Windows which does not support --read-only 2780 testRequires(c, DaemonIsLinux, NotUserNamespace) 2781 touch := "touch " + strings.Join(filenames, " ") 2782 out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch) 2783 c.Assert(err, checker.NotNil) 2784 2785 for _, f := range filenames { 2786 expected := "touch: " + f + ": Read-only file system" 2787 c.Assert(out, checker.Contains, expected) 2788 } 2789 2790 out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch) 2791 c.Assert(err, checker.NotNil) 2792 2793 for _, f := range filenames { 2794 expected := "touch: " + f + ": Read-only file system" 2795 c.Assert(out, checker.Contains, expected) 2796 } 2797 } 2798 2799 func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) { 2800 // Not applicable on Windows which does not support --link 2801 // --read-only + userns has remount issues 2802 testRequires(c, DaemonIsLinux, NotUserNamespace) 2803 2804 dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") 2805 2806 out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts") 2807 if !strings.Contains(string(out), "testlinked") { 2808 c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled") 2809 } 2810 } 2811 2812 func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) { 2813 // Not applicable on Windows which does not support either --read-only or --dns. 2814 // --read-only + userns has remount issues 2815 testRequires(c, DaemonIsLinux, NotUserNamespace) 2816 2817 out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf") 2818 if !strings.Contains(string(out), "1.1.1.1") { 2819 c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used") 2820 } 2821 } 2822 2823 func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) { 2824 // Not applicable on Windows which does not support --read-only 2825 // --read-only + userns has remount issues 2826 testRequires(c, DaemonIsLinux, NotUserNamespace) 2827 2828 out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts") 2829 if !strings.Contains(string(out), "testreadonly") { 2830 c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used") 2831 } 2832 } 2833 2834 func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) { 2835 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 2836 dockerCmd(c, "run", "-d", "--name", "voltest", "-v", prefix+"/foo", "busybox", "sleep", "60") 2837 dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "sleep", "60") 2838 2839 // Remove the main volume container and restart the consuming container 2840 dockerCmd(c, "rm", "-f", "voltest") 2841 2842 // This should not fail since the volumes-from were already applied 2843 dockerCmd(c, "restart", "restarter") 2844 } 2845 2846 // run container with --rm should remove container if exit code != 0 2847 func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) { 2848 name := "flowers" 2849 out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists") 2850 if err == nil { 2851 c.Fatal("Expected docker run to fail", out, err) 2852 } 2853 2854 out, err = getAllContainers() 2855 if err != nil { 2856 c.Fatal(out, err) 2857 } 2858 2859 if out != "" { 2860 c.Fatal("Expected not to have containers", out) 2861 } 2862 } 2863 2864 func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) { 2865 name := "sparkles" 2866 out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound") 2867 if err == nil { 2868 c.Fatal("Expected docker run to fail", out, err) 2869 } 2870 2871 out, err = getAllContainers() 2872 if err != nil { 2873 c.Fatal(out, err) 2874 } 2875 2876 if out != "" { 2877 c.Fatal("Expected not to have containers", out) 2878 } 2879 } 2880 2881 func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) { 2882 // Not applicable on Windows as uses Unix specific functionality 2883 testRequires(c, DaemonIsLinux, NotUserNamespace) 2884 name := "ibuildthecloud" 2885 dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi") 2886 2887 c.Assert(waitRun(name), check.IsNil) 2888 2889 errchan := make(chan error) 2890 go func() { 2891 if out, _, err := dockerCmdWithError("kill", name); err != nil { 2892 errchan <- fmt.Errorf("%v:\n%s", err, out) 2893 } 2894 close(errchan) 2895 }() 2896 select { 2897 case err := <-errchan: 2898 c.Assert(err, check.IsNil) 2899 case <-time.After(5 * time.Second): 2900 c.Fatal("Kill container timed out") 2901 } 2902 } 2903 2904 func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) { 2905 // TODO Windows. This may be possible to enable once Windows supports 2906 // memory limits on containers 2907 testRequires(c, DaemonIsLinux) 2908 // this memory limit is 1 byte less than the min, which is 4MB 2909 // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22 2910 out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox") 2911 if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") { 2912 c.Fatalf("expected run to fail when using too low a memory limit: %q", out) 2913 } 2914 } 2915 2916 func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) { 2917 // Not applicable on Windows as uses Unix specific functionality 2918 testRequires(c, DaemonIsLinux) 2919 _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version") 2920 if err == nil || code == 0 { 2921 c.Fatal("standard container should not be able to write to /proc/asound") 2922 } 2923 } 2924 2925 func (s *DockerSuite) TestRunReadProcTimer(c *check.C) { 2926 // Not applicable on Windows as uses Unix specific functionality 2927 testRequires(c, DaemonIsLinux) 2928 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats") 2929 if code != 0 { 2930 return 2931 } 2932 if err != nil { 2933 c.Fatal(err) 2934 } 2935 if strings.Trim(out, "\n ") != "" { 2936 c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out) 2937 } 2938 } 2939 2940 func (s *DockerSuite) TestRunReadProcLatency(c *check.C) { 2941 // Not applicable on Windows as uses Unix specific functionality 2942 testRequires(c, DaemonIsLinux) 2943 // some kernels don't have this configured so skip the test if this file is not found 2944 // on the host running the tests. 2945 if _, err := os.Stat("/proc/latency_stats"); err != nil { 2946 c.Skip("kernel doesn't have latency_stats configured") 2947 return 2948 } 2949 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats") 2950 if code != 0 { 2951 return 2952 } 2953 if err != nil { 2954 c.Fatal(err) 2955 } 2956 if strings.Trim(out, "\n ") != "" { 2957 c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out) 2958 } 2959 } 2960 2961 func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) { 2962 // Not applicable on Windows as uses Unix specific functionality 2963 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2964 2965 testReadPaths := []string{ 2966 "/proc/latency_stats", 2967 "/proc/timer_stats", 2968 "/proc/kcore", 2969 } 2970 for i, filePath := range testReadPaths { 2971 name := fmt.Sprintf("procsieve-%d", i) 2972 shellCmd := fmt.Sprintf("exec 3<%s", filePath) 2973 2974 out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 2975 if exitCode != 0 { 2976 return 2977 } 2978 if err != nil { 2979 c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err) 2980 } 2981 } 2982 } 2983 2984 func (s *DockerSuite) TestMountIntoProc(c *check.C) { 2985 // Not applicable on Windows as uses Unix specific functionality 2986 testRequires(c, DaemonIsLinux) 2987 _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true") 2988 if err == nil || code == 0 { 2989 c.Fatal("container should not be able to mount into /proc") 2990 } 2991 } 2992 2993 func (s *DockerSuite) TestMountIntoSys(c *check.C) { 2994 // Not applicable on Windows as uses Unix specific functionality 2995 testRequires(c, DaemonIsLinux) 2996 testRequires(c, NotUserNamespace) 2997 dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") 2998 } 2999 3000 func (s *DockerSuite) TestRunUnshareProc(c *check.C) { 3001 // Not applicable on Windows as uses Unix specific functionality 3002 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 3003 3004 // In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run. 3005 errChan := make(chan error) 3006 3007 go func() { 3008 name := "acidburn" 3009 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount") 3010 if err == nil || 3011 !(strings.Contains(strings.ToLower(out), "permission denied") || 3012 strings.Contains(strings.ToLower(out), "operation not permitted")) { 3013 errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err) 3014 } else { 3015 errChan <- nil 3016 } 3017 }() 3018 3019 go func() { 3020 name := "cereal" 3021 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 3022 if err == nil || 3023 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 3024 strings.Contains(strings.ToLower(out), "permission denied") || 3025 strings.Contains(strings.ToLower(out), "operation not permitted")) { 3026 errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 3027 } else { 3028 errChan <- nil 3029 } 3030 }() 3031 3032 /* Ensure still fails if running privileged with the default policy */ 3033 go func() { 3034 name := "crashoverride" 3035 out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=docker-default", "--name", name, "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 3036 if err == nil || 3037 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 3038 strings.Contains(strings.ToLower(out), "permission denied") || 3039 strings.Contains(strings.ToLower(out), "operation not permitted")) { 3040 errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 3041 } else { 3042 errChan <- nil 3043 } 3044 }() 3045 3046 for i := 0; i < 3; i++ { 3047 err := <-errChan 3048 if err != nil { 3049 c.Fatal(err) 3050 } 3051 } 3052 } 3053 3054 func (s *DockerSuite) TestRunPublishPort(c *check.C) { 3055 // TODO Windows: This may be possible once Windows moves to libnetwork and CNM 3056 testRequires(c, DaemonIsLinux) 3057 dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") 3058 out, _ := dockerCmd(c, "port", "test") 3059 out = strings.Trim(out, "\r\n") 3060 if out != "" { 3061 c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out) 3062 } 3063 } 3064 3065 // Issue #10184. 3066 func (s *DockerSuite) TestDevicePermissions(c *check.C) { 3067 // Not applicable on Windows as uses Unix specific functionality 3068 testRequires(c, DaemonIsLinux) 3069 const permissions = "crw-rw-rw-" 3070 out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") 3071 if status != 0 { 3072 c.Fatalf("expected status 0, got %d", status) 3073 } 3074 if !strings.HasPrefix(out, permissions) { 3075 c.Fatalf("output should begin with %q, got %q", permissions, out) 3076 } 3077 } 3078 3079 func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) { 3080 // Not applicable on Windows as uses Unix specific functionality 3081 testRequires(c, DaemonIsLinux) 3082 out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok") 3083 3084 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 3085 c.Fatalf("expected output ok received %s", actual) 3086 } 3087 } 3088 3089 // https://github.com/docker/docker/pull/14498 3090 func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { 3091 // TODO Windows post TP4. Enable the read-only bits once they are 3092 // supported on the platform. 3093 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 3094 3095 dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true") 3096 if daemonPlatform != "windows" { 3097 dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") 3098 } 3099 dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") 3100 3101 if daemonPlatform != "windows" { 3102 mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") 3103 c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) 3104 if mRO.RW { 3105 c.Fatalf("Expected RO volume was RW") 3106 } 3107 } 3108 3109 mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test") 3110 c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) 3111 if !mRW.RW { 3112 c.Fatalf("Expected RW volume was RO") 3113 } 3114 } 3115 3116 func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) { 3117 // Not applicable on Windows as uses Unix specific functionality 3118 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 3119 3120 testWritePaths := []string{ 3121 /* modprobe and core_pattern should both be denied by generic 3122 * policy of denials for /proc/sys/kernel. These files have been 3123 * picked to be checked as they are particularly sensitive to writes */ 3124 "/proc/sys/kernel/modprobe", 3125 "/proc/sys/kernel/core_pattern", 3126 "/proc/sysrq-trigger", 3127 "/proc/kcore", 3128 } 3129 for i, filePath := range testWritePaths { 3130 name := fmt.Sprintf("writeprocsieve-%d", i) 3131 3132 shellCmd := fmt.Sprintf("exec 3>%s", filePath) 3133 out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 3134 if code != 0 { 3135 return 3136 } 3137 if err != nil { 3138 c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err) 3139 } 3140 } 3141 } 3142 3143 func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) { 3144 // Not applicable on Windows as uses Unix specific functionality 3145 testRequires(c, SameHostDaemon, DaemonIsLinux) 3146 3147 expected := "test123" 3148 3149 filename := createTmpFile(c, expected) 3150 defer os.Remove(filename) 3151 3152 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3153 3154 for i := range nwfiles { 3155 actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i]) 3156 if actual != expected { 3157 c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual) 3158 } 3159 } 3160 } 3161 3162 func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) { 3163 // Not applicable on Windows as uses Unix specific functionality 3164 testRequires(c, SameHostDaemon, DaemonIsLinux) 3165 3166 filename := createTmpFile(c, "test123") 3167 defer os.Remove(filename) 3168 3169 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3170 3171 for i := range nwfiles { 3172 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i]) 3173 if err == nil || exitCode == 0 { 3174 c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode) 3175 } 3176 } 3177 } 3178 3179 func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) { 3180 // Not applicable on Windows as uses Unix specific functionality 3181 // --read-only + userns has remount issues 3182 testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) 3183 3184 filename := createTmpFile(c, "test123") 3185 defer os.Remove(filename) 3186 3187 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3188 3189 for i := range nwfiles { 3190 _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i]) 3191 if exitCode != 0 { 3192 c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3193 } 3194 } 3195 3196 for i := range nwfiles { 3197 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i]) 3198 if err == nil || exitCode == 0 { 3199 c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3200 } 3201 } 3202 } 3203 3204 func (s *DockerTrustSuite) TestTrustedRun(c *check.C) { 3205 // Windows does not support this functionality 3206 testRequires(c, DaemonIsLinux) 3207 repoName := s.setupTrustedImage(c, "trusted-run") 3208 3209 // Try run 3210 runCmd := exec.Command(dockerBinary, "run", repoName) 3211 s.trustedCmd(runCmd) 3212 out, _, err := runCommandWithOutput(runCmd) 3213 if err != nil { 3214 c.Fatalf("Error running trusted run: %s\n%s\n", err, out) 3215 } 3216 3217 if !strings.Contains(string(out), "Tagging") { 3218 c.Fatalf("Missing expected output on trusted push:\n%s", out) 3219 } 3220 3221 dockerCmd(c, "rmi", repoName) 3222 3223 // Try untrusted run to ensure we pushed the tag to the registry 3224 runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName) 3225 s.trustedCmd(runCmd) 3226 out, _, err = runCommandWithOutput(runCmd) 3227 if err != nil { 3228 c.Fatalf("Error running trusted run: %s\n%s", err, out) 3229 } 3230 3231 if !strings.Contains(string(out), "Status: Downloaded") { 3232 c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out) 3233 } 3234 } 3235 3236 func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) { 3237 // Windows does not support this functionality 3238 testRequires(c, DaemonIsLinux) 3239 repoName := fmt.Sprintf("%v/dockercliuntrusted/runtest:latest", privateRegistryURL) 3240 // tag the image and upload it to the private registry 3241 dockerCmd(c, "tag", "busybox", repoName) 3242 dockerCmd(c, "push", repoName) 3243 dockerCmd(c, "rmi", repoName) 3244 3245 // Try trusted run on untrusted tag 3246 runCmd := exec.Command(dockerBinary, "run", repoName) 3247 s.trustedCmd(runCmd) 3248 out, _, err := runCommandWithOutput(runCmd) 3249 if err == nil { 3250 c.Fatalf("Error expected when running trusted run with:\n%s", out) 3251 } 3252 3253 if !strings.Contains(string(out), "does not have trust data for") { 3254 c.Fatalf("Missing expected output on trusted run:\n%s", out) 3255 } 3256 } 3257 3258 func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) { 3259 // Windows does not support this functionality 3260 testRequires(c, DaemonIsLinux) 3261 c.Skip("Currently changes system time, causing instability") 3262 repoName := s.setupTrustedImage(c, "trusted-run-expired") 3263 3264 // Certificates have 10 years of expiration 3265 elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11) 3266 3267 runAtDifferentDate(elevenYearsFromNow, func() { 3268 // Try run 3269 runCmd := exec.Command(dockerBinary, "run", repoName) 3270 s.trustedCmd(runCmd) 3271 out, _, err := runCommandWithOutput(runCmd) 3272 if err == nil { 3273 c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out) 3274 } 3275 3276 if !strings.Contains(string(out), "could not validate the path to a trusted root") { 3277 c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out) 3278 } 3279 }) 3280 3281 runAtDifferentDate(elevenYearsFromNow, func() { 3282 // Try run 3283 runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName) 3284 s.trustedCmd(runCmd) 3285 out, _, err := runCommandWithOutput(runCmd) 3286 if err != nil { 3287 c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out) 3288 } 3289 3290 if !strings.Contains(string(out), "Status: Downloaded") { 3291 c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out) 3292 } 3293 }) 3294 } 3295 3296 func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) { 3297 // Windows does not support this functionality 3298 testRequires(c, DaemonIsLinux) 3299 repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL) 3300 evilLocalConfigDir, err := ioutil.TempDir("", "evilrun-local-config-dir") 3301 if err != nil { 3302 c.Fatalf("Failed to create local temp dir") 3303 } 3304 3305 // tag the image and upload it to the private registry 3306 dockerCmd(c, "tag", "busybox", repoName) 3307 3308 pushCmd := exec.Command(dockerBinary, "push", repoName) 3309 s.trustedCmd(pushCmd) 3310 out, _, err := runCommandWithOutput(pushCmd) 3311 if err != nil { 3312 c.Fatalf("Error running trusted push: %s\n%s", err, out) 3313 } 3314 if !strings.Contains(string(out), "Signing and pushing trust metadata") { 3315 c.Fatalf("Missing expected output on trusted push:\n%s", out) 3316 } 3317 3318 dockerCmd(c, "rmi", repoName) 3319 3320 // Try run 3321 runCmd := exec.Command(dockerBinary, "run", repoName) 3322 s.trustedCmd(runCmd) 3323 out, _, err = runCommandWithOutput(runCmd) 3324 if err != nil { 3325 c.Fatalf("Error running trusted run: %s\n%s", err, out) 3326 } 3327 3328 if !strings.Contains(string(out), "Tagging") { 3329 c.Fatalf("Missing expected output on trusted push:\n%s", out) 3330 } 3331 3332 dockerCmd(c, "rmi", repoName) 3333 3334 // Kill the notary server, start a new "evil" one. 3335 s.not.Close() 3336 s.not, err = newTestNotary(c) 3337 if err != nil { 3338 c.Fatalf("Restarting notary server failed.") 3339 } 3340 3341 // In order to make an evil server, lets re-init a client (with a different trust dir) and push new data. 3342 // tag an image and upload it to the private registry 3343 dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName) 3344 3345 // Push up to the new server 3346 pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName) 3347 s.trustedCmd(pushCmd) 3348 out, _, err = runCommandWithOutput(pushCmd) 3349 if err != nil { 3350 c.Fatalf("Error running trusted push: %s\n%s", err, out) 3351 } 3352 if !strings.Contains(string(out), "Signing and pushing trust metadata") { 3353 c.Fatalf("Missing expected output on trusted push:\n%s", out) 3354 } 3355 3356 // Now, try running with the original client from this new trust server. This should fallback to our cached timestamp and metadata. 3357 runCmd = exec.Command(dockerBinary, "run", repoName) 3358 s.trustedCmd(runCmd) 3359 out, _, err = runCommandWithOutput(runCmd) 3360 3361 if err != nil { 3362 c.Fatalf("Error falling back to cached trust data: %s\n%s", err, out) 3363 } 3364 if !strings.Contains(string(out), "Error while downloading remote metadata, using cached timestamp") { 3365 c.Fatalf("Missing expected output on trusted push:\n%s", out) 3366 } 3367 } 3368 3369 func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) { 3370 // Not applicable on Windows as uses Unix specific functionality 3371 testRequires(c, DaemonIsLinux, SameHostDaemon) 3372 3373 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 3374 id := strings.TrimSpace(out) 3375 c.Assert(waitRun(id), check.IsNil) 3376 pid1 := inspectField(c, id, "State.Pid") 3377 3378 _, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 3379 if err != nil { 3380 c.Fatal(err) 3381 } 3382 } 3383 3384 func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) { 3385 // Not applicable on Windows as uses Unix specific functionality 3386 testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotGCCGO) 3387 3388 // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace 3389 // itself, but pid>1 should not be able to trace pid1. 3390 _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net") 3391 if exitCode == 0 { 3392 c.Fatal("ptrace was not successfully restricted by AppArmor") 3393 } 3394 } 3395 3396 func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) { 3397 // Not applicable on Windows as uses Unix specific functionality 3398 testRequires(c, DaemonIsLinux, SameHostDaemon, Apparmor) 3399 3400 _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net") 3401 if exitCode != 0 { 3402 c.Fatal("ptrace of self failed.") 3403 } 3404 } 3405 3406 func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) { 3407 // Not applicable on Windows as uses Unix specific functionality 3408 testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotUserNamespace) 3409 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo") 3410 if exitCode == 0 { 3411 // If our test failed, attempt to repair the host system... 3412 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo") 3413 if exitCode == 0 { 3414 c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.") 3415 } 3416 } 3417 } 3418 3419 func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) { 3420 // Not applicable on Windows as uses Unix specific functionality 3421 testRequires(c, DaemonIsLinux) 3422 3423 dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") 3424 } 3425 3426 // run create container failed should clean up the container 3427 func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) { 3428 // TODO Windows. This may be possible to enable once link is supported 3429 testRequires(c, DaemonIsLinux) 3430 name := "unique_name" 3431 _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox") 3432 c.Assert(err, check.NotNil, check.Commentf("Expected docker run to fail!")) 3433 3434 containerID, err := inspectFieldWithError(name, "Id") 3435 c.Assert(err, checker.NotNil, check.Commentf("Expected not to have this container: %s!", containerID)) 3436 c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID)) 3437 } 3438 3439 func (s *DockerSuite) TestRunNamedVolume(c *check.C) { 3440 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3441 testRequires(c, DaemonIsLinux) 3442 dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar") 3443 3444 out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") 3445 c.Assert(strings.TrimSpace(out), check.Equals, "hello") 3446 3447 out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") 3448 c.Assert(strings.TrimSpace(out), check.Equals, "hello") 3449 } 3450 3451 func (s *DockerSuite) TestRunWithUlimits(c *check.C) { 3452 // Not applicable on Windows as uses Unix specific functionality 3453 testRequires(c, DaemonIsLinux) 3454 3455 out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n") 3456 ul := strings.TrimSpace(out) 3457 if ul != "42" { 3458 c.Fatalf("expected `ulimit -n` to be 42, got %s", ul) 3459 } 3460 } 3461 3462 func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) { 3463 // Not applicable on Windows as uses Unix specific functionality 3464 testRequires(c, DaemonIsLinux) 3465 3466 cgroupParent := "test" 3467 name := "cgroup-test" 3468 3469 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3470 if err != nil { 3471 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) 3472 } 3473 cgroupPaths := parseCgroupPaths(string(out)) 3474 if len(cgroupPaths) == 0 { 3475 c.Fatalf("unexpected output - %q", string(out)) 3476 } 3477 id, err := getIDByName(name) 3478 c.Assert(err, check.IsNil) 3479 expectedCgroup := path.Join(cgroupParent, id) 3480 found := false 3481 for _, path := range cgroupPaths { 3482 if strings.HasSuffix(path, expectedCgroup) { 3483 found = true 3484 break 3485 } 3486 } 3487 if !found { 3488 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3489 } 3490 } 3491 3492 func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) { 3493 // Not applicable on Windows as uses Unix specific functionality 3494 testRequires(c, DaemonIsLinux) 3495 3496 cgroupParent := "/cgroup-parent/test" 3497 name := "cgroup-test" 3498 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3499 if err != nil { 3500 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) 3501 } 3502 cgroupPaths := parseCgroupPaths(string(out)) 3503 if len(cgroupPaths) == 0 { 3504 c.Fatalf("unexpected output - %q", string(out)) 3505 } 3506 id, err := getIDByName(name) 3507 c.Assert(err, check.IsNil) 3508 expectedCgroup := path.Join(cgroupParent, id) 3509 found := false 3510 for _, path := range cgroupPaths { 3511 if strings.HasSuffix(path, expectedCgroup) { 3512 found = true 3513 break 3514 } 3515 } 3516 if !found { 3517 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3518 } 3519 } 3520 3521 // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /. 3522 func (s *DockerSuite) TestRunInvalidCgroupParent(c *check.C) { 3523 // Not applicable on Windows as uses Unix specific functionality 3524 testRequires(c, DaemonIsLinux) 3525 3526 cgroupParent := "../../../../../../../../SHOULD_NOT_EXIST" 3527 cleanCgroupParent := "SHOULD_NOT_EXIST" 3528 name := "cgroup-invalid-test" 3529 3530 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3531 if err != nil { 3532 // XXX: This may include a daemon crash. 3533 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) 3534 } 3535 3536 // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue. 3537 if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) { 3538 c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!") 3539 } 3540 3541 cgroupPaths := parseCgroupPaths(string(out)) 3542 if len(cgroupPaths) == 0 { 3543 c.Fatalf("unexpected output - %q", string(out)) 3544 } 3545 id, err := getIDByName(name) 3546 c.Assert(err, check.IsNil) 3547 expectedCgroup := path.Join(cleanCgroupParent, id) 3548 found := false 3549 for _, path := range cgroupPaths { 3550 if strings.HasSuffix(path, expectedCgroup) { 3551 found = true 3552 break 3553 } 3554 } 3555 if !found { 3556 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3557 } 3558 } 3559 3560 // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /. 3561 func (s *DockerSuite) TestRunAbsoluteInvalidCgroupParent(c *check.C) { 3562 // Not applicable on Windows as uses Unix specific functionality 3563 testRequires(c, DaemonIsLinux) 3564 3565 cgroupParent := "/../../../../../../../../SHOULD_NOT_EXIST" 3566 cleanCgroupParent := "/SHOULD_NOT_EXIST" 3567 name := "cgroup-absolute-invalid-test" 3568 3569 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3570 if err != nil { 3571 // XXX: This may include a daemon crash. 3572 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) 3573 } 3574 3575 // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue. 3576 if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) { 3577 c.Fatalf("SECURITY: --cgroup-parent with /../../ garbage paths cause files to be created in the host (this is bad) !!") 3578 } 3579 3580 cgroupPaths := parseCgroupPaths(string(out)) 3581 if len(cgroupPaths) == 0 { 3582 c.Fatalf("unexpected output - %q", string(out)) 3583 } 3584 id, err := getIDByName(name) 3585 c.Assert(err, check.IsNil) 3586 expectedCgroup := path.Join(cleanCgroupParent, id) 3587 found := false 3588 for _, path := range cgroupPaths { 3589 if strings.HasSuffix(path, expectedCgroup) { 3590 found = true 3591 break 3592 } 3593 } 3594 if !found { 3595 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3596 } 3597 } 3598 3599 func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) { 3600 // Not applicable on Windows as uses Unix specific functionality 3601 // --read-only + userns has remount issues 3602 testRequires(c, DaemonIsLinux, NotUserNamespace) 3603 3604 filename := "/sys/fs/cgroup/devices/test123" 3605 out, _, err := dockerCmdWithError("run", "busybox", "touch", filename) 3606 if err == nil { 3607 c.Fatal("expected cgroup mount point to be read-only, touch file should fail") 3608 } 3609 expected := "Read-only file system" 3610 if !strings.Contains(out, expected) { 3611 c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) 3612 } 3613 } 3614 3615 func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *check.C) { 3616 // Not applicable on Windows which does not support --net=container 3617 testRequires(c, DaemonIsLinux, NotUserNamespace) 3618 out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true") 3619 if err == nil || !strings.Contains(out, "cannot join own network") { 3620 c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out) 3621 } 3622 } 3623 3624 func (s *DockerSuite) TestRunContainerNetModeWithDnsMacHosts(c *check.C) { 3625 // Not applicable on Windows which does not support --net=container 3626 testRequires(c, DaemonIsLinux, NotUserNamespace) 3627 out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top") 3628 if err != nil { 3629 c.Fatalf("failed to run container: %v, output: %q", err, out) 3630 } 3631 3632 out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox") 3633 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) { 3634 c.Fatalf("run --net=container with --dns should error out") 3635 } 3636 3637 out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox") 3638 if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) { 3639 c.Fatalf("run --net=container with --mac-address should error out") 3640 } 3641 3642 out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox") 3643 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) { 3644 c.Fatalf("run --net=container with --add-host should error out") 3645 } 3646 } 3647 3648 func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) { 3649 // Not applicable on Windows which does not support --net=container 3650 testRequires(c, DaemonIsLinux, NotUserNamespace) 3651 dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") 3652 3653 out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox") 3654 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3655 c.Fatalf("run --net=container with -p should error out") 3656 } 3657 3658 out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox") 3659 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3660 c.Fatalf("run --net=container with -P should error out") 3661 } 3662 3663 out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox") 3664 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) { 3665 c.Fatalf("run --net=container with --expose should error out") 3666 } 3667 } 3668 3669 func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) { 3670 // Not applicable on Windows which does not support --net=container or --link 3671 testRequires(c, DaemonIsLinux, NotUserNamespace) 3672 dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") 3673 dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") 3674 dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") 3675 dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") 3676 dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") 3677 } 3678 3679 func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) { 3680 // TODO Windows: This may be possible to convert. 3681 testRequires(c, DaemonIsLinux) 3682 out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up") 3683 3684 var ( 3685 count = 0 3686 parts = strings.Split(out, "\n") 3687 ) 3688 3689 for _, l := range parts { 3690 if l != "" { 3691 count++ 3692 } 3693 } 3694 3695 if count != 1 { 3696 c.Fatalf("Wrong interface count in container %d", count) 3697 } 3698 3699 if !strings.HasPrefix(out, "1: lo") { 3700 c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out) 3701 } 3702 } 3703 3704 // Issue #4681 3705 func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) { 3706 if daemonPlatform == "windows" { 3707 dockerCmd(c, "run", "--net=none", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1") 3708 } else { 3709 dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") 3710 } 3711 } 3712 3713 func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) { 3714 // Windows does not support --net=container 3715 testRequires(c, DaemonIsLinux, ExecSupport, NotUserNamespace) 3716 3717 dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") 3718 out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname") 3719 out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname") 3720 3721 if out1 != out { 3722 c.Fatal("containers with shared net namespace should have same hostname") 3723 } 3724 } 3725 3726 func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) { 3727 // TODO Windows: Network settings are not currently propagated. This may 3728 // be resolved in the future with the move to libnetwork and CNM. 3729 testRequires(c, DaemonIsLinux) 3730 out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top") 3731 id := strings.TrimSpace(out) 3732 res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress") 3733 if res != "" { 3734 c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res) 3735 } 3736 } 3737 3738 func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) { 3739 // Not applicable as Windows does not support --net=host 3740 testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace) 3741 dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3742 dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") 3743 dockerCmd(c, "stop", "first") 3744 dockerCmd(c, "stop", "second") 3745 } 3746 3747 func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *check.C) { 3748 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3749 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork") 3750 dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top") 3751 c.Assert(waitRun("first"), check.IsNil) 3752 dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first") 3753 } 3754 3755 func (s *DockerSuite) TestContainersInMultipleNetworks(c *check.C) { 3756 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3757 // Create 2 networks using bridge driver 3758 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3759 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3760 // Run and connect containers to testnetwork1 3761 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3762 c.Assert(waitRun("first"), check.IsNil) 3763 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3764 c.Assert(waitRun("second"), check.IsNil) 3765 // Check connectivity between containers in testnetwork2 3766 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3767 // Connect containers to testnetwork2 3768 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3769 dockerCmd(c, "network", "connect", "testnetwork2", "second") 3770 // Check connectivity between containers 3771 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3772 } 3773 3774 func (s *DockerSuite) TestContainersNetworkIsolation(c *check.C) { 3775 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3776 // Create 2 networks using bridge driver 3777 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3778 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3779 // Run 1 container in testnetwork1 and another in testnetwork2 3780 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3781 c.Assert(waitRun("first"), check.IsNil) 3782 dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top") 3783 c.Assert(waitRun("second"), check.IsNil) 3784 3785 // Check Isolation between containers : ping must fail 3786 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3787 c.Assert(err, check.NotNil) 3788 // Connect first container to testnetwork2 3789 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3790 // ping must succeed now 3791 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3792 c.Assert(err, check.IsNil) 3793 3794 // Disconnect first container from testnetwork2 3795 dockerCmd(c, "network", "disconnect", "testnetwork2", "first") 3796 // ping must fail again 3797 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3798 c.Assert(err, check.NotNil) 3799 } 3800 3801 func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) { 3802 testRequires(c, DaemonIsLinux, NotUserNamespace) 3803 // Create 2 networks using bridge driver 3804 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3805 // Run and connect containers to testnetwork1 3806 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3807 c.Assert(waitRun("first"), check.IsNil) 3808 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3809 c.Assert(waitRun("second"), check.IsNil) 3810 // Network delete with active containers must fail 3811 _, _, err := dockerCmdWithError("network", "rm", "testnetwork1") 3812 c.Assert(err, check.NotNil) 3813 3814 dockerCmd(c, "stop", "first") 3815 _, _, err = dockerCmdWithError("network", "rm", "testnetwork1") 3816 c.Assert(err, check.NotNil) 3817 } 3818 3819 func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) { 3820 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3821 // Create 2 networks using bridge driver 3822 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3823 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3824 3825 // Run and connect containers to testnetwork1 3826 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3827 c.Assert(waitRun("first"), check.IsNil) 3828 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3829 c.Assert(waitRun("second"), check.IsNil) 3830 // Check connectivity between containers in testnetwork2 3831 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3832 // Connect containers to testnetwork2 3833 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3834 dockerCmd(c, "network", "connect", "testnetwork2", "second") 3835 // Check connectivity between containers 3836 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3837 3838 // Stop second container and test ping failures on both networks 3839 dockerCmd(c, "stop", "second") 3840 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1") 3841 c.Assert(err, check.NotNil) 3842 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2") 3843 c.Assert(err, check.NotNil) 3844 3845 // Start second container and connectivity must be restored on both networks 3846 dockerCmd(c, "start", "second") 3847 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3848 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3849 } 3850 3851 func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *check.C) { 3852 testRequires(c, DaemonIsLinux, NotUserNamespace) 3853 // Run a container with --net=host 3854 dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3855 c.Assert(waitRun("first"), check.IsNil) 3856 3857 // Create a network using bridge driver 3858 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3859 3860 // Connecting to the user defined network must fail 3861 _, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3862 c.Assert(err, check.NotNil) 3863 } 3864 3865 func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) { 3866 testRequires(c, DaemonIsLinux, NotUserNamespace) 3867 dockerCmd(c, "run", "-d", "--name=first", "busybox", "top") 3868 c.Assert(waitRun("first"), check.IsNil) 3869 // Run second container in first container's network namespace 3870 dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top") 3871 c.Assert(waitRun("second"), check.IsNil) 3872 3873 // Create a network using bridge driver 3874 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3875 3876 // Connecting to the user defined network must fail 3877 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second") 3878 c.Assert(err, check.NotNil) 3879 c.Assert(out, checker.Contains, runconfig.ErrConflictSharedNetwork.Error()) 3880 } 3881 3882 func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) { 3883 testRequires(c, DaemonIsLinux, NotUserNamespace) 3884 dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top") 3885 c.Assert(waitRun("first"), check.IsNil) 3886 3887 // Create a network using bridge driver 3888 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3889 3890 // Connecting to the user defined network must fail 3891 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3892 c.Assert(err, check.NotNil) 3893 c.Assert(out, checker.Contains, runconfig.ErrConflictNoNetwork.Error()) 3894 3895 // create a container connected to testnetwork1 3896 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3897 c.Assert(waitRun("second"), check.IsNil) 3898 3899 // Connect second container to none network. it must fail as well 3900 _, _, err = dockerCmdWithError("network", "connect", "none", "second") 3901 c.Assert(err, check.NotNil) 3902 } 3903 3904 // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited 3905 func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *check.C) { 3906 cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true") 3907 in, err := cmd.StdinPipe() 3908 c.Assert(err, check.IsNil) 3909 defer in.Close() 3910 c.Assert(cmd.Start(), check.IsNil) 3911 3912 waitChan := make(chan error) 3913 go func() { 3914 waitChan <- cmd.Wait() 3915 }() 3916 3917 select { 3918 case err := <-waitChan: 3919 c.Assert(err, check.IsNil) 3920 case <-time.After(30 * time.Second): 3921 c.Fatal("timeout waiting for command to exit") 3922 } 3923 } 3924 3925 func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *check.C) { 3926 // TODO Windows: This needs validation (error out) in the daemon. 3927 testRequires(c, DaemonIsLinux) 3928 out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true") 3929 c.Assert(err, check.NotNil) 3930 expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n" 3931 if !(strings.Contains(out, expected) || exitCode == 125) { 3932 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3933 } 3934 } 3935 3936 func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *check.C) { 3937 // TODO Windows: This needs validation (error out) in the daemon. 3938 testRequires(c, DaemonIsLinux) 3939 out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true") 3940 c.Assert(err, check.NotNil) 3941 expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n" 3942 if !(strings.Contains(out, expected) || exitCode == 125) { 3943 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3944 } 3945 } 3946 3947 // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127' 3948 func (s *DockerSuite) TestRunNonExecutableCmd(c *check.C) { 3949 name := "testNonExecutableCmd" 3950 runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "foo") 3951 _, exit, _ := runCommandWithOutput(runCmd) 3952 stateExitCode := findContainerExitCode(c, name) 3953 if !(exit == 127 && strings.Contains(stateExitCode, "127")) { 3954 c.Fatalf("Run non-executable command should have errored with exit code 127, but we got exit: %d, State.ExitCode: %s", exit, stateExitCode) 3955 } 3956 } 3957 3958 // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127. 3959 func (s *DockerSuite) TestRunNonExistingCmd(c *check.C) { 3960 name := "testNonExistingCmd" 3961 runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "/bin/foo") 3962 _, exit, _ := runCommandWithOutput(runCmd) 3963 stateExitCode := findContainerExitCode(c, name) 3964 if !(exit == 127 && strings.Contains(stateExitCode, "127")) { 3965 c.Fatalf("Run non-existing command should have errored with exit code 127, but we got exit: %d, State.ExitCode: %s", exit, stateExitCode) 3966 } 3967 } 3968 3969 // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or 3970 // 127 on Windows. The difference is that in Windows, the container must be started 3971 // as that's when the check is made (and yes, by it's design...) 3972 func (s *DockerSuite) TestCmdCannotBeInvoked(c *check.C) { 3973 expected := 126 3974 if daemonPlatform == "windows" { 3975 expected = 127 3976 } 3977 name := "testCmdCannotBeInvoked" 3978 runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "/etc") 3979 _, exit, _ := runCommandWithOutput(runCmd) 3980 stateExitCode := findContainerExitCode(c, name) 3981 if !(exit == expected && strings.Contains(stateExitCode, strconv.Itoa(expected))) { 3982 c.Fatalf("Run cmd that cannot be invoked should have errored with code %d, but we got exit: %d, State.ExitCode: %s", expected, exit, stateExitCode) 3983 } 3984 } 3985 3986 // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains 'Unable to find image' 3987 func (s *DockerSuite) TestRunNonExistingImage(c *check.C) { 3988 runCmd := exec.Command(dockerBinary, "run", "foo") 3989 out, exit, err := runCommandWithOutput(runCmd) 3990 if !(err != nil && exit == 125 && strings.Contains(out, "Unable to find image")) { 3991 c.Fatalf("Run non-existing image should have errored with 'Unable to find image' code 125, but we got out: %s, exit: %d, err: %s", out, exit, err) 3992 } 3993 } 3994 3995 // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed 3996 func (s *DockerSuite) TestDockerFails(c *check.C) { 3997 runCmd := exec.Command(dockerBinary, "run", "-foo", "busybox") 3998 out, exit, err := runCommandWithOutput(runCmd) 3999 if !(err != nil && exit == 125) { 4000 c.Fatalf("Docker run with flag not defined should exit with 125, but we got out: %s, exit: %d, err: %s", out, exit, err) 4001 } 4002 } 4003 4004 // TestRunInvalidReference invokes docker run with a bad reference. 4005 func (s *DockerSuite) TestRunInvalidReference(c *check.C) { 4006 out, exit, _ := dockerCmdWithError("run", "busybox@foo") 4007 if exit == 0 { 4008 c.Fatalf("expected non-zero exist code; received %d", exit) 4009 } 4010 4011 if !strings.Contains(out, "Error parsing reference") { 4012 c.Fatalf(`Expected "Error parsing reference" in output; got: %s`, out) 4013 } 4014 } 4015 4016 // Test fix for issue #17854 4017 func (s *DockerSuite) TestRunInitLayerPathOwnership(c *check.C) { 4018 // Not applicable on Windows as it does not support Linux uid/gid ownership 4019 testRequires(c, DaemonIsLinux) 4020 name := "testetcfileownership" 4021 _, err := buildImage(name, 4022 `FROM busybox 4023 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 4024 RUN echo 'dockerio:x:1001:' >> /etc/group 4025 RUN chown dockerio:dockerio /etc`, 4026 true) 4027 if err != nil { 4028 c.Fatal(err) 4029 } 4030 4031 // Test that dockerio ownership of /etc is retained at runtime 4032 out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc") 4033 out = strings.TrimSpace(out) 4034 if out != "dockerio:dockerio" { 4035 c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out) 4036 } 4037 } 4038 4039 func (s *DockerSuite) TestRunWithOomScoreAdj(c *check.C) { 4040 testRequires(c, DaemonIsLinux) 4041 4042 expected := "642" 4043 out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj") 4044 oomScoreAdj := strings.TrimSpace(out) 4045 if oomScoreAdj != "642" { 4046 c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj) 4047 } 4048 } 4049 4050 func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *check.C) { 4051 testRequires(c, DaemonIsLinux) 4052 4053 out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true") 4054 c.Assert(err, check.NotNil) 4055 expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]." 4056 if !strings.Contains(out, expected) { 4057 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 4058 } 4059 out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true") 4060 c.Assert(err, check.NotNil) 4061 expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]." 4062 if !strings.Contains(out, expected) { 4063 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 4064 } 4065 } 4066 4067 func (s *DockerSuite) TestRunVolumesMountedAsShared(c *check.C) { 4068 // Volume propagation is linux only. Also it creates directories for 4069 // bind mounting, so needs to be same host. 4070 testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) 4071 4072 // Prepare a source directory to bind mount 4073 tmpDir, err := ioutil.TempDir("", "volume-source") 4074 if err != nil { 4075 c.Fatal(err) 4076 } 4077 defer os.RemoveAll(tmpDir) 4078 4079 if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil { 4080 c.Fatal(err) 4081 } 4082 4083 // Convert this directory into a shared mount point so that we do 4084 // not rely on propagation properties of parent mount. 4085 cmd := exec.Command("mount", "--bind", tmpDir, tmpDir) 4086 if _, err = runCommand(cmd); err != nil { 4087 c.Fatal(err) 4088 } 4089 4090 cmd = exec.Command("mount", "--make-private", "--make-shared", tmpDir) 4091 if _, err = runCommand(cmd); err != nil { 4092 c.Fatal(err) 4093 } 4094 4095 dockerCmd(c, "run", "--privileged", "-v", fmt.Sprintf("%s:/volume-dest:shared", tmpDir), "busybox", "mount", "--bind", "/volume-dest/mnt1", "/volume-dest/mnt1") 4096 4097 // Make sure a bind mount under a shared volume propagated to host. 4098 if mounted, _ := mount.Mounted(path.Join(tmpDir, "mnt1")); !mounted { 4099 c.Fatalf("Bind mount under shared volume did not propagate to host") 4100 } 4101 4102 mount.Unmount(path.Join(tmpDir, "mnt1")) 4103 } 4104 4105 func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *check.C) { 4106 // Volume propagation is linux only. Also it creates directories for 4107 // bind mounting, so needs to be same host. 4108 testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) 4109 4110 // Prepare a source directory to bind mount 4111 tmpDir, err := ioutil.TempDir("", "volume-source") 4112 if err != nil { 4113 c.Fatal(err) 4114 } 4115 defer os.RemoveAll(tmpDir) 4116 4117 if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil { 4118 c.Fatal(err) 4119 } 4120 4121 // Prepare a source directory with file in it. We will bind mount this 4122 // direcotry and see if file shows up. 4123 tmpDir2, err := ioutil.TempDir("", "volume-source2") 4124 if err != nil { 4125 c.Fatal(err) 4126 } 4127 defer os.RemoveAll(tmpDir2) 4128 4129 if err := ioutil.WriteFile(path.Join(tmpDir2, "slave-testfile"), []byte("Test"), 0644); err != nil { 4130 c.Fatal(err) 4131 } 4132 4133 // Convert this directory into a shared mount point so that we do 4134 // not rely on propagation properties of parent mount. 4135 cmd := exec.Command("mount", "--bind", tmpDir, tmpDir) 4136 if _, err = runCommand(cmd); err != nil { 4137 c.Fatal(err) 4138 } 4139 4140 cmd = exec.Command("mount", "--make-private", "--make-shared", tmpDir) 4141 if _, err = runCommand(cmd); err != nil { 4142 c.Fatal(err) 4143 } 4144 4145 dockerCmd(c, "run", "-i", "-d", "--name", "parent", "-v", fmt.Sprintf("%s:/volume-dest:slave", tmpDir), "busybox", "top") 4146 4147 // Bind mount tmpDir2/ onto tmpDir/mnt1. If mount propagates inside 4148 // container then contents of tmpDir2/slave-testfile should become 4149 // visible at "/volume-dest/mnt1/slave-testfile" 4150 cmd = exec.Command("mount", "--bind", tmpDir2, path.Join(tmpDir, "mnt1")) 4151 if _, err = runCommand(cmd); err != nil { 4152 c.Fatal(err) 4153 } 4154 4155 out, _ := dockerCmd(c, "exec", "parent", "cat", "/volume-dest/mnt1/slave-testfile") 4156 4157 mount.Unmount(path.Join(tmpDir, "mnt1")) 4158 4159 if out != "Test" { 4160 c.Fatalf("Bind mount under slave volume did not propagate to container") 4161 } 4162 } 4163 4164 func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *check.C) { 4165 testRequires(c, DaemonIsLinux, NotUserNamespace) 4166 out, exitcode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile") 4167 4168 if exitcode == 0 { 4169 c.Fatalf("expected non-zero exit code; received %d", exitcode) 4170 } 4171 4172 if expected := "Invalid volume specification"; !strings.Contains(out, expected) { 4173 c.Fatalf(`Expected %q in output; got: %s`, expected, out) 4174 } 4175 } 4176 4177 func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *check.C) { 4178 testRequires(c, DaemonIsLinux) 4179 4180 testImg := "testvolumecopy" 4181 _, err := buildImage(testImg, ` 4182 FROM busybox 4183 RUN mkdir -p /foo && echo hello > /foo/hello 4184 `, true) 4185 c.Assert(err, check.IsNil) 4186 4187 dockerCmd(c, "run", "-v", "foo:/foo", testImg) 4188 out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello") 4189 c.Assert(strings.TrimSpace(out), check.Equals, "hello") 4190 } 4191 4192 func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *check.C) { 4193 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 4194 4195 dockerCmd(c, "volume", "create", "--name", "test") 4196 4197 dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 4198 dockerCmd(c, "volume", "inspect", "test") 4199 out, _ := dockerCmd(c, "volume", "ls", "-q") 4200 c.Assert(strings.TrimSpace(out), checker.Equals, "test") 4201 4202 dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 4203 dockerCmd(c, "rm", "-fv", "test") 4204 dockerCmd(c, "volume", "inspect", "test") 4205 out, _ = dockerCmd(c, "volume", "ls", "-q") 4206 c.Assert(strings.TrimSpace(out), checker.Equals, "test") 4207 } 4208 4209 func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) { 4210 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 4211 4212 dockerCmd(c, "volume", "create", "--name", "test") 4213 dockerCmd(c, "run", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 4214 dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") 4215 4216 // Remove the parent so there are not other references to the volumes 4217 dockerCmd(c, "rm", "-f", "parent") 4218 // now remove the child and ensure the named volume (and only the named volume) still exists 4219 dockerCmd(c, "rm", "-fv", "child") 4220 dockerCmd(c, "volume", "inspect", "test") 4221 out, _ := dockerCmd(c, "volume", "ls", "-q") 4222 c.Assert(strings.TrimSpace(out), checker.Equals, "test") 4223 } 4224 4225 func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) { 4226 nroutines, err := getGoroutineNumber() 4227 c.Assert(err, checker.IsNil) 4228 4229 runSleepingContainer(c, "--name=test", "-p", "8000:8000") 4230 4231 // Wait until container is fully up and running 4232 c.Assert(waitRun("test"), check.IsNil) 4233 4234 out, _, err := dockerCmdWithError("run", "-p", "8000:8000", "busybox", "true") 4235 c.Assert(err, checker.NotNil) 4236 // check for windows error as well 4237 // TODO Windows Post TP5. Fix the error message string 4238 c.Assert(strings.Contains(string(out), "port is already allocated") || 4239 strings.Contains(string(out), "were not connected because a duplicate name exists") || 4240 strings.Contains(string(out), "HNS failed with error : Failed to create endpoint"), checker.Equals, true, check.Commentf("Output: %s", out)) 4241 dockerCmd(c, "rm", "-f", "test") 4242 4243 // NGoroutines is not updated right away, so we need to wait before failing 4244 c.Assert(waitForGoroutines(nroutines), checker.IsNil) 4245 } 4246 4247 // Test for one character directory name case (#20122) 4248 func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *check.C) { 4249 testRequires(c, DaemonIsLinux) 4250 4251 out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo") 4252 c.Assert(strings.TrimSpace(out), checker.Equals, "/foo") 4253 } 4254 4255 func (s *DockerSuite) TestRunVolumeCopyFlag(c *check.C) { 4256 testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume 4257 _, err := buildImage("volumecopy", 4258 `FROM busybox 4259 RUN mkdir /foo && echo hello > /foo/bar 4260 CMD cat /foo/bar`, 4261 true, 4262 ) 4263 c.Assert(err, checker.IsNil) 4264 4265 dockerCmd(c, "volume", "create", "--name=test") 4266 4267 // test with the nocopy flag 4268 out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy") 4269 c.Assert(err, checker.NotNil, check.Commentf(out)) 4270 // test default behavior which is to copy for non-binds 4271 out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") 4272 c.Assert(strings.TrimSpace(out), checker.Equals, "hello") 4273 // error out when the volume is already populated 4274 out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy") 4275 c.Assert(err, checker.NotNil, check.Commentf(out)) 4276 // do not error out when copy isn't explicitly set even though it's already populated 4277 out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") 4278 c.Assert(strings.TrimSpace(out), checker.Equals, "hello") 4279 4280 // do not allow copy modes on volumes-from 4281 dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") 4282 out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true") 4283 c.Assert(err, checker.NotNil, check.Commentf(out)) 4284 out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true") 4285 c.Assert(err, checker.NotNil, check.Commentf(out)) 4286 4287 // do not allow copy modes on binds 4288 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true") 4289 c.Assert(err, checker.NotNil, check.Commentf(out)) 4290 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true") 4291 c.Assert(err, checker.NotNil, check.Commentf(out)) 4292 } 4293 4294 func (s *DockerSuite) TestRunTooLongHostname(c *check.C) { 4295 // Test case in #21445 4296 hostname1 := "this-is-a-way-too-long-hostname-but-it-should-give-a-nice-error.local" 4297 out, _, err := dockerCmdWithError("run", "--hostname", hostname1, "busybox", "echo", "test") 4298 c.Assert(err, checker.NotNil, check.Commentf("Expected docker run to fail!")) 4299 c.Assert(out, checker.Contains, "invalid hostname format for --hostname:", check.Commentf("Expected to have 'invalid hostname format for --hostname:' in the output, get: %s!", out)) 4300 4301 // HOST_NAME_MAX=64 so 65 bytes will fail 4302 hostname2 := "this-is-a-hostname-with-65-bytes-so-it-should-give-an-error.local" 4303 out, _, err = dockerCmdWithError("run", "--hostname", hostname2, "busybox", "echo", "test") 4304 c.Assert(err, checker.NotNil, check.Commentf("Expected docker run to fail!")) 4305 c.Assert(out, checker.Contains, "invalid hostname format for --hostname:", check.Commentf("Expected to have 'invalid hostname format for --hostname:' in the output, get: %s!", out)) 4306 4307 // 64 bytes will be OK 4308 hostname3 := "this-is-a-hostname-with-64-bytes-so-will-not-give-an-error.local" 4309 dockerCmd(c, "run", "--hostname", hostname3, "busybox", "echo", "test") 4310 }