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