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