github.com/afbjorklund/moby@v20.10.5+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/Microsoft/hcsshim/osversion" 27 "github.com/docker/docker/client" 28 "github.com/docker/docker/integration-cli/cli" 29 "github.com/docker/docker/integration-cli/cli/build" 30 "github.com/docker/docker/pkg/stringid" 31 "github.com/docker/docker/runconfig" 32 "github.com/docker/docker/testutil" 33 "github.com/docker/docker/testutil/fakecontext" 34 "github.com/docker/go-connections/nat" 35 "github.com/docker/libnetwork/resolvconf" 36 "github.com/docker/libnetwork/types" 37 "github.com/moby/sys/mountinfo" 38 "gotest.tools/v3/assert" 39 "gotest.tools/v3/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", "example.com") 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 := mountinfo.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, 1) 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(osversion.RS5)) 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, 1) 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, 1) 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 memory limits on containers 2829 testRequires(c, DaemonIsLinux) 2830 // this memory limit is 1 byte less than the min (daemon.linuxMinMemory), which is 6MB (6291456 bytes) 2831 out, _, err := dockerCmdWithError("create", "-m", "6291455", "busybox") 2832 if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 6MB") { 2833 c.Fatalf("expected run to fail when using too low a memory limit: %q", out) 2834 } 2835 } 2836 2837 func (s *DockerSuite) TestRunWriteToProcAsound(c *testing.T) { 2838 // Not applicable on Windows as uses Unix specific functionality 2839 testRequires(c, DaemonIsLinux) 2840 _, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version") 2841 if err == nil || code == 0 { 2842 c.Fatal("standard container should not be able to write to /proc/asound") 2843 } 2844 } 2845 2846 func (s *DockerSuite) TestRunReadProcTimer(c *testing.T) { 2847 // Not applicable on Windows as uses Unix specific functionality 2848 testRequires(c, DaemonIsLinux) 2849 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats") 2850 if code != 0 { 2851 return 2852 } 2853 if err != nil { 2854 c.Fatal(err) 2855 } 2856 if strings.Trim(out, "\n ") != "" { 2857 c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out) 2858 } 2859 } 2860 2861 func (s *DockerSuite) TestRunReadProcLatency(c *testing.T) { 2862 // Not applicable on Windows as uses Unix specific functionality 2863 testRequires(c, DaemonIsLinux) 2864 // some kernels don't have this configured so skip the test if this file is not found 2865 // on the host running the tests. 2866 if _, err := os.Stat("/proc/latency_stats"); err != nil { 2867 c.Skip("kernel doesn't have latency_stats configured") 2868 return 2869 } 2870 out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats") 2871 if code != 0 { 2872 return 2873 } 2874 if err != nil { 2875 c.Fatal(err) 2876 } 2877 if strings.Trim(out, "\n ") != "" { 2878 c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out) 2879 } 2880 } 2881 2882 func (s *DockerSuite) TestRunReadFilteredProc(c *testing.T) { 2883 // Not applicable on Windows as uses Unix specific functionality 2884 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2885 2886 testReadPaths := []string{ 2887 "/proc/latency_stats", 2888 "/proc/timer_stats", 2889 "/proc/kcore", 2890 } 2891 for i, filePath := range testReadPaths { 2892 name := fmt.Sprintf("procsieve-%d", i) 2893 shellCmd := fmt.Sprintf("exec 3<%s", filePath) 2894 2895 out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 2896 if exitCode != 0 { 2897 return 2898 } 2899 if err != nil { 2900 c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err) 2901 } 2902 } 2903 } 2904 2905 func (s *DockerSuite) TestMountIntoProc(c *testing.T) { 2906 // Not applicable on Windows as uses Unix specific functionality 2907 testRequires(c, DaemonIsLinux) 2908 _, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true") 2909 if err == nil || code == 0 { 2910 c.Fatal("container should not be able to mount into /proc") 2911 } 2912 } 2913 2914 func (s *DockerSuite) TestMountIntoSys(c *testing.T) { 2915 // Not applicable on Windows as uses Unix specific functionality 2916 testRequires(c, DaemonIsLinux) 2917 testRequires(c, NotUserNamespace) 2918 dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") 2919 } 2920 2921 func (s *DockerSuite) TestRunUnshareProc(c *testing.T) { 2922 // Not applicable on Windows as uses Unix specific functionality 2923 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 2924 2925 // In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run. 2926 errChan := make(chan error) 2927 2928 go func() { 2929 name := "acidburn" 2930 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:bullseye", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount") 2931 if err == nil || 2932 !(strings.Contains(strings.ToLower(out), "permission denied") || 2933 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2934 errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err) 2935 } else { 2936 errChan <- nil 2937 } 2938 }() 2939 2940 go func() { 2941 name := "cereal" 2942 out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:bullseye", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 2943 if err == nil || 2944 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 2945 strings.Contains(strings.ToLower(out), "permission denied") || 2946 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2947 errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 2948 } else { 2949 errChan <- nil 2950 } 2951 }() 2952 2953 /* Ensure still fails if running privileged with the default policy */ 2954 go func() { 2955 name := "crashoverride" 2956 out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=docker-default", "--name", name, "debian:bullseye", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 2957 if err == nil || 2958 !(strings.Contains(strings.ToLower(out), "mount: cannot mount none") || 2959 strings.Contains(strings.ToLower(out), "permission denied") || 2960 strings.Contains(strings.ToLower(out), "operation not permitted")) { 2961 errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err) 2962 } else { 2963 errChan <- nil 2964 } 2965 }() 2966 2967 var retErr error 2968 for i := 0; i < 3; i++ { 2969 err := <-errChan 2970 if retErr == nil && err != nil { 2971 retErr = err 2972 } 2973 } 2974 if retErr != nil { 2975 c.Fatal(retErr) 2976 } 2977 } 2978 2979 func (s *DockerSuite) TestRunPublishPort(c *testing.T) { 2980 // TODO Windows: This may be possible once Windows moves to libnetwork and CNM 2981 testRequires(c, DaemonIsLinux) 2982 dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") 2983 out, _ := dockerCmd(c, "port", "test") 2984 out = strings.Trim(out, "\r\n") 2985 if out != "" { 2986 c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out) 2987 } 2988 } 2989 2990 // Issue #10184. 2991 func (s *DockerSuite) TestDevicePermissions(c *testing.T) { 2992 // Not applicable on Windows as uses Unix specific functionality 2993 testRequires(c, DaemonIsLinux) 2994 const permissions = "crw-rw-rw-" 2995 out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") 2996 if status != 0 { 2997 c.Fatalf("expected status 0, got %d", status) 2998 } 2999 if !strings.HasPrefix(out, permissions) { 3000 c.Fatalf("output should begin with %q, got %q", permissions, out) 3001 } 3002 } 3003 3004 func (s *DockerSuite) TestRunCapAddCHOWN(c *testing.T) { 3005 // Not applicable on Windows as uses Unix specific functionality 3006 testRequires(c, DaemonIsLinux) 3007 out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok") 3008 3009 if actual := strings.Trim(out, "\r\n"); actual != "ok" { 3010 c.Fatalf("expected output ok received %s", actual) 3011 } 3012 } 3013 3014 // https://github.com/docker/docker/pull/14498 3015 func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *testing.T) { 3016 prefix, slash := getPrefixAndSlashFromDaemonPlatform() 3017 3018 dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true") 3019 3020 dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") 3021 dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") 3022 3023 if testEnv.OSType != "windows" { 3024 mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") 3025 assert.NilError(c, err, "failed to inspect mount point") 3026 if mRO.RW { 3027 c.Fatalf("Expected RO volume was RW") 3028 } 3029 } 3030 3031 mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test") 3032 assert.NilError(c, err, "failed to inspect mount point") 3033 if !mRW.RW { 3034 c.Fatalf("Expected RW volume was RO") 3035 } 3036 } 3037 3038 func (s *DockerSuite) TestRunWriteFilteredProc(c *testing.T) { 3039 // Not applicable on Windows as uses Unix specific functionality 3040 testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace) 3041 3042 testWritePaths := []string{ 3043 /* modprobe and core_pattern should both be denied by generic 3044 * policy of denials for /proc/sys/kernel. These files have been 3045 * picked to be checked as they are particularly sensitive to writes */ 3046 "/proc/sys/kernel/modprobe", 3047 "/proc/sys/kernel/core_pattern", 3048 "/proc/sysrq-trigger", 3049 "/proc/kcore", 3050 } 3051 for i, filePath := range testWritePaths { 3052 name := fmt.Sprintf("writeprocsieve-%d", i) 3053 3054 shellCmd := fmt.Sprintf("exec 3>%s", filePath) 3055 out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) 3056 if code != 0 { 3057 return 3058 } 3059 if err != nil { 3060 c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err) 3061 } 3062 } 3063 } 3064 3065 func (s *DockerSuite) TestRunNetworkFilesBindMount(c *testing.T) { 3066 // Not applicable on Windows as uses Unix specific functionality 3067 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 3068 3069 expected := "test123" 3070 3071 filename := createTmpFile(c, expected) 3072 defer os.Remove(filename) 3073 3074 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3075 if err := os.Chmod(filename, 0646); err != nil { 3076 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3077 } 3078 3079 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3080 3081 for i := range nwfiles { 3082 actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i]) 3083 if actual != expected { 3084 c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual) 3085 } 3086 } 3087 } 3088 3089 func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *testing.T) { 3090 // Not applicable on Windows as uses Unix specific functionality 3091 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 3092 3093 filename := createTmpFile(c, "test123") 3094 defer os.Remove(filename) 3095 3096 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3097 if err := os.Chmod(filename, 0646); err != nil { 3098 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3099 } 3100 3101 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3102 3103 for i := range nwfiles { 3104 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i]) 3105 if err == nil || exitCode == 0 { 3106 c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode) 3107 } 3108 } 3109 } 3110 3111 func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *testing.T) { 3112 // Not applicable on Windows as uses Unix specific functionality 3113 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, UserNamespaceROMount) 3114 3115 filename := createTmpFile(c, "test123") 3116 defer os.Remove(filename) 3117 3118 // for user namespaced test runs, the temp file must be accessible to unprivileged root 3119 if err := os.Chmod(filename, 0646); err != nil { 3120 c.Fatalf("error modifying permissions of %s: %v", filename, err) 3121 } 3122 3123 nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} 3124 3125 for i := range nwfiles { 3126 _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i]) 3127 if exitCode != 0 { 3128 c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3129 } 3130 } 3131 3132 for i := range nwfiles { 3133 _, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i]) 3134 if err == nil || exitCode == 0 { 3135 c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode) 3136 } 3137 } 3138 } 3139 3140 func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *testing.T) { 3141 // Not applicable on Windows as uses Unix specific functionality 3142 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 3143 3144 out, _ := dockerCmd(c, "run", "-d", "busybox", "top") 3145 id := strings.TrimSpace(out) 3146 assert.NilError(c, waitRun(id)) 3147 pid1 := inspectField(c, id, "State.Pid") 3148 3149 _, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) 3150 if err != nil { 3151 c.Fatal(err) 3152 } 3153 } 3154 3155 func (s *DockerSuite) TestAppArmorDeniesPtrace(c *testing.T) { 3156 // Not applicable on Windows as uses Unix specific functionality 3157 testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux) 3158 3159 // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace 3160 // itself, but pid>1 should not be able to trace pid1. 3161 _, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net") 3162 if exitCode == 0 { 3163 c.Fatal("ptrace was not successfully restricted by AppArmor") 3164 } 3165 } 3166 3167 func (s *DockerSuite) TestAppArmorTraceSelf(c *testing.T) { 3168 // Not applicable on Windows as uses Unix specific functionality 3169 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, Apparmor) 3170 3171 _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net") 3172 if exitCode != 0 { 3173 c.Fatal("ptrace of self failed.") 3174 } 3175 } 3176 3177 func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *testing.T) { 3178 // Not applicable on Windows as uses Unix specific functionality 3179 testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux, NotUserNamespace) 3180 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo") 3181 if exitCode == 0 { 3182 // If our test failed, attempt to repair the host system... 3183 _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo") 3184 if exitCode == 0 { 3185 c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.") 3186 } 3187 } 3188 } 3189 3190 func (s *DockerSuite) TestRunCapAddSYSTIME(c *testing.T) { 3191 // Not applicable on Windows as uses Unix specific functionality 3192 testRequires(c, DaemonIsLinux) 3193 3194 dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") 3195 } 3196 3197 // run create container failed should clean up the container 3198 func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *testing.T) { 3199 // TODO Windows. This may be possible to enable once link is supported 3200 testRequires(c, DaemonIsLinux) 3201 name := "unique_name" 3202 _, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox") 3203 assert.Assert(c, err != nil, "Expected docker run to fail!") 3204 3205 containerID, err := inspectFieldWithError(name, "Id") 3206 assert.Assert(c, err != nil, "Expected not to have this container: %s!", containerID) 3207 assert.Equal(c, containerID, "", fmt.Sprintf("Expected not to have this container: %s!", containerID)) 3208 } 3209 3210 func (s *DockerSuite) TestRunNamedVolume(c *testing.T) { 3211 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3212 testRequires(c, DaemonIsLinux) 3213 dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar") 3214 3215 out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") 3216 assert.Equal(c, strings.TrimSpace(out), "hello") 3217 3218 out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") 3219 assert.Equal(c, strings.TrimSpace(out), "hello") 3220 } 3221 3222 func (s *DockerSuite) TestRunWithUlimits(c *testing.T) { 3223 // Not applicable on Windows as uses Unix specific functionality 3224 testRequires(c, DaemonIsLinux) 3225 3226 out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n") 3227 ul := strings.TrimSpace(out) 3228 if ul != "42" { 3229 c.Fatalf("expected `ulimit -n` to be 42, got %s", ul) 3230 } 3231 } 3232 3233 func (s *DockerSuite) TestRunContainerWithCgroupParent(c *testing.T) { 3234 // Not applicable on Windows as uses Unix specific functionality 3235 testRequires(c, DaemonIsLinux) 3236 3237 // cgroup-parent relative path 3238 testRunContainerWithCgroupParent(c, "test", "cgroup-test") 3239 3240 // cgroup-parent absolute path 3241 testRunContainerWithCgroupParent(c, "/cgroup-parent/test", "cgroup-test-absolute") 3242 } 3243 3244 func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) { 3245 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3246 if err != nil { 3247 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err) 3248 } 3249 cgroupPaths := ParseCgroupPaths(out) 3250 if len(cgroupPaths) == 0 { 3251 c.Fatalf("unexpected output - %q", out) 3252 } 3253 id := getIDByName(c, name) 3254 expectedCgroup := path.Join(cgroupParent, id) 3255 found := false 3256 for _, path := range cgroupPaths { 3257 if strings.HasSuffix(path, expectedCgroup) { 3258 found = true 3259 break 3260 } 3261 } 3262 if !found { 3263 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3264 } 3265 } 3266 3267 // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /. 3268 func (s *DockerSuite) TestRunInvalidCgroupParent(c *testing.T) { 3269 // Not applicable on Windows as uses Unix specific functionality 3270 testRequires(c, DaemonIsLinux) 3271 3272 testRunInvalidCgroupParent(c, "../../../../../../../../SHOULD_NOT_EXIST", "SHOULD_NOT_EXIST", "cgroup-invalid-test") 3273 3274 testRunInvalidCgroupParent(c, "/../../../../../../../../SHOULD_NOT_EXIST", "/SHOULD_NOT_EXIST", "cgroup-absolute-invalid-test") 3275 } 3276 3277 func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, name string) { 3278 out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") 3279 if err != nil { 3280 // XXX: This may include a daemon crash. 3281 c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err) 3282 } 3283 3284 // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue. 3285 if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) { 3286 c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!") 3287 } 3288 3289 cgroupPaths := ParseCgroupPaths(out) 3290 if len(cgroupPaths) == 0 { 3291 c.Fatalf("unexpected output - %q", out) 3292 } 3293 id := getIDByName(c, name) 3294 expectedCgroup := path.Join(cleanCgroupParent, id) 3295 found := false 3296 for _, path := range cgroupPaths { 3297 if strings.HasSuffix(path, expectedCgroup) { 3298 found = true 3299 break 3300 } 3301 } 3302 if !found { 3303 c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) 3304 } 3305 } 3306 3307 func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *testing.T) { 3308 // Not applicable on Windows as uses Unix specific functionality 3309 // --read-only + userns has remount issues 3310 testRequires(c, DaemonIsLinux, NotUserNamespace) 3311 3312 filename := "/sys/fs/cgroup/devices/test123" 3313 out, _, err := dockerCmdWithError("run", "busybox", "touch", filename) 3314 if err == nil { 3315 c.Fatal("expected cgroup mount point to be read-only, touch file should fail") 3316 } 3317 expected := "Read-only file system" 3318 if !strings.Contains(out, expected) { 3319 c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) 3320 } 3321 } 3322 3323 func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *testing.T) { 3324 // Not applicable on Windows which does not support --net=container 3325 testRequires(c, DaemonIsLinux) 3326 out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true") 3327 if err == nil || !strings.Contains(out, "cannot join own network") { 3328 c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out) 3329 } 3330 } 3331 3332 func (s *DockerSuite) TestRunContainerNetModeWithDNSMacHosts(c *testing.T) { 3333 // Not applicable on Windows which does not support --net=container 3334 testRequires(c, DaemonIsLinux) 3335 out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top") 3336 if err != nil { 3337 c.Fatalf("failed to run container: %v, output: %q", err, out) 3338 } 3339 3340 out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox") 3341 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) { 3342 c.Fatalf("run --net=container with --dns should error out") 3343 } 3344 3345 out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox") 3346 if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) { 3347 c.Fatalf("run --net=container with --mac-address should error out") 3348 } 3349 3350 out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox") 3351 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) { 3352 c.Fatalf("run --net=container with --add-host should error out") 3353 } 3354 } 3355 3356 func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *testing.T) { 3357 // Not applicable on Windows which does not support --net=container 3358 testRequires(c, DaemonIsLinux) 3359 dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") 3360 3361 out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox") 3362 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3363 c.Fatalf("run --net=container with -p should error out") 3364 } 3365 3366 out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox") 3367 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { 3368 c.Fatalf("run --net=container with -P should error out") 3369 } 3370 3371 out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox") 3372 if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) { 3373 c.Fatalf("run --net=container with --expose should error out") 3374 } 3375 } 3376 3377 func (s *DockerSuite) TestRunLinkToContainerNetMode(c *testing.T) { 3378 // Not applicable on Windows which does not support --net=container or --link 3379 testRequires(c, DaemonIsLinux) 3380 dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") 3381 dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") 3382 dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") 3383 dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") 3384 dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") 3385 } 3386 3387 func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *testing.T) { 3388 // TODO Windows: This may be possible to convert. 3389 testRequires(c, DaemonIsLinux) 3390 out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up") 3391 3392 var ( 3393 count = 0 3394 parts = strings.Split(out, "\n") 3395 ) 3396 3397 for _, l := range parts { 3398 if l != "" { 3399 count++ 3400 } 3401 } 3402 3403 if count != 1 { 3404 c.Fatalf("Wrong interface count in container %d", count) 3405 } 3406 3407 if !strings.HasPrefix(out, "1: lo") { 3408 c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out) 3409 } 3410 } 3411 3412 // Issue #4681 3413 func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *testing.T) { 3414 if testEnv.OSType == "windows" { 3415 dockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") 3416 } else { 3417 dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") 3418 } 3419 } 3420 3421 func (s *DockerSuite) TestRunModeNetContainerHostname(c *testing.T) { 3422 // Windows does not support --net=container 3423 testRequires(c, DaemonIsLinux) 3424 3425 dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") 3426 out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname") 3427 out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname") 3428 3429 if out1 != out { 3430 c.Fatal("containers with shared net namespace should have same hostname") 3431 } 3432 } 3433 3434 func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *testing.T) { 3435 // TODO Windows: Network settings are not currently propagated. This may 3436 // be resolved in the future with the move to libnetwork and CNM. 3437 testRequires(c, DaemonIsLinux) 3438 out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top") 3439 id := strings.TrimSpace(out) 3440 res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress") 3441 if res != "" { 3442 c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res) 3443 } 3444 } 3445 3446 func (s *DockerSuite) TestTwoContainersInNetHost(c *testing.T) { 3447 // Not applicable as Windows does not support --net=host 3448 testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace) 3449 dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3450 dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") 3451 dockerCmd(c, "stop", "first") 3452 dockerCmd(c, "stop", "second") 3453 } 3454 3455 func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *testing.T) { 3456 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3457 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork") 3458 dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top") 3459 assert.Assert(c, waitRun("first") == nil) 3460 dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first") 3461 } 3462 3463 func (s *DockerSuite) TestContainersInMultipleNetworks(c *testing.T) { 3464 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3465 // Create 2 networks using bridge driver 3466 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3467 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3468 // Run and connect containers to testnetwork1 3469 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3470 assert.Assert(c, waitRun("first") == nil) 3471 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3472 assert.Assert(c, waitRun("second") == nil) 3473 // Check connectivity between containers in testnetwork2 3474 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3475 // Connect containers to testnetwork2 3476 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3477 dockerCmd(c, "network", "connect", "testnetwork2", "second") 3478 // Check connectivity between containers 3479 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3480 } 3481 3482 func (s *DockerSuite) TestContainersNetworkIsolation(c *testing.T) { 3483 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3484 // Create 2 networks using bridge driver 3485 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3486 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3487 // Run 1 container in testnetwork1 and another in testnetwork2 3488 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3489 assert.Assert(c, waitRun("first") == nil) 3490 dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top") 3491 assert.Assert(c, waitRun("second") == nil) 3492 3493 // Check Isolation between containers : ping must fail 3494 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3495 assert.ErrorContains(c, err, "") 3496 // Connect first container to testnetwork2 3497 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3498 // ping must succeed now 3499 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3500 assert.NilError(c, err) 3501 3502 // Disconnect first container from testnetwork2 3503 dockerCmd(c, "network", "disconnect", "testnetwork2", "first") 3504 // ping must fail again 3505 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") 3506 assert.ErrorContains(c, err, "") 3507 } 3508 3509 func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *testing.T) { 3510 testRequires(c, DaemonIsLinux, NotUserNamespace) 3511 // Create 2 networks using bridge driver 3512 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3513 // Run and connect containers to testnetwork1 3514 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3515 assert.Assert(c, waitRun("first") == nil) 3516 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3517 assert.Assert(c, waitRun("second") == nil) 3518 // Network delete with active containers must fail 3519 _, _, err := dockerCmdWithError("network", "rm", "testnetwork1") 3520 assert.ErrorContains(c, err, "") 3521 3522 dockerCmd(c, "stop", "first") 3523 _, _, err = dockerCmdWithError("network", "rm", "testnetwork1") 3524 assert.ErrorContains(c, err, "") 3525 } 3526 3527 func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *testing.T) { 3528 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm) 3529 // Create 2 networks using bridge driver 3530 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3531 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") 3532 3533 // Run and connect containers to testnetwork1 3534 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") 3535 assert.Assert(c, waitRun("first") == nil) 3536 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3537 assert.Assert(c, waitRun("second") == nil) 3538 // Check connectivity between containers in testnetwork2 3539 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3540 // Connect containers to testnetwork2 3541 dockerCmd(c, "network", "connect", "testnetwork2", "first") 3542 dockerCmd(c, "network", "connect", "testnetwork2", "second") 3543 // Check connectivity between containers 3544 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3545 3546 // Stop second container and test ping failures on both networks 3547 dockerCmd(c, "stop", "second") 3548 _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1") 3549 assert.ErrorContains(c, err, "") 3550 _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2") 3551 assert.ErrorContains(c, err, "") 3552 3553 // Start second container and connectivity must be restored on both networks 3554 dockerCmd(c, "start", "second") 3555 dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") 3556 dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") 3557 } 3558 3559 func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *testing.T) { 3560 testRequires(c, DaemonIsLinux, NotUserNamespace) 3561 // Run a container with --net=host 3562 dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") 3563 assert.Assert(c, waitRun("first") == nil) 3564 3565 // Create a network using bridge driver 3566 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3567 3568 // Connecting to the user defined network must fail 3569 _, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3570 assert.ErrorContains(c, err, "") 3571 } 3572 3573 func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *testing.T) { 3574 testRequires(c, DaemonIsLinux) 3575 dockerCmd(c, "run", "-d", "--name=first", "busybox", "top") 3576 assert.Assert(c, waitRun("first") == nil) 3577 // Run second container in first container's network namespace 3578 dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top") 3579 assert.Assert(c, waitRun("second") == nil) 3580 3581 // Create a network using bridge driver 3582 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3583 3584 // Connecting to the user defined network must fail 3585 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second") 3586 assert.ErrorContains(c, err, "") 3587 assert.Assert(c, strings.Contains(out, runconfig.ErrConflictSharedNetwork.Error())) 3588 } 3589 3590 func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *testing.T) { 3591 testRequires(c, DaemonIsLinux) 3592 dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top") 3593 assert.Assert(c, waitRun("first") == nil) 3594 3595 // Create a network using bridge driver 3596 dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") 3597 3598 // Connecting to the user defined network must fail 3599 out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") 3600 assert.ErrorContains(c, err, "") 3601 assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNoNetwork.Error())) 3602 // create a container connected to testnetwork1 3603 dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") 3604 assert.Assert(c, waitRun("second") == nil) 3605 3606 // Connect second container to none network. it must fail as well 3607 _, _, err = dockerCmdWithError("network", "connect", "none", "second") 3608 assert.ErrorContains(c, err, "") 3609 } 3610 3611 // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited 3612 func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *testing.T) { 3613 cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true") 3614 in, err := cmd.StdinPipe() 3615 assert.NilError(c, err) 3616 defer in.Close() 3617 stdout := bytes.NewBuffer(nil) 3618 cmd.Stdout = stdout 3619 cmd.Stderr = stdout 3620 assert.Assert(c, cmd.Start() == nil) 3621 3622 waitChan := make(chan error, 1) 3623 go func() { 3624 waitChan <- cmd.Wait() 3625 }() 3626 3627 select { 3628 case err := <-waitChan: 3629 assert.Assert(c, err == nil, stdout.String()) 3630 case <-time.After(30 * time.Second): 3631 c.Fatal("timeout waiting for command to exit") 3632 } 3633 } 3634 3635 func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *testing.T) { 3636 // TODO Windows: This needs validation (error out) in the daemon. 3637 testRequires(c, DaemonIsLinux) 3638 out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true") 3639 assert.ErrorContains(c, err, "") 3640 expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n" 3641 if !(strings.Contains(out, expected) || exitCode == 125) { 3642 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3643 } 3644 } 3645 3646 func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *testing.T) { 3647 // TODO Windows: This needs validation (error out) in the daemon. 3648 testRequires(c, DaemonIsLinux) 3649 out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true") 3650 assert.ErrorContains(c, err, "") 3651 expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n" 3652 if !(strings.Contains(out, expected) || exitCode == 125) { 3653 c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) 3654 } 3655 } 3656 3657 // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127' 3658 func (s *DockerSuite) TestRunNonExecutableCmd(c *testing.T) { 3659 name := "testNonExecutableCmd" 3660 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "foo").Assert(c, icmd.Expected{ 3661 ExitCode: 127, 3662 Error: "exit status 127", 3663 }) 3664 } 3665 3666 // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127. 3667 func (s *DockerSuite) TestRunNonExistingCmd(c *testing.T) { 3668 name := "testNonExistingCmd" 3669 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/bin/foo").Assert(c, icmd.Expected{ 3670 ExitCode: 127, 3671 Error: "exit status 127", 3672 }) 3673 } 3674 3675 // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or 3676 // 127 on Windows. The difference is that in Windows, the container must be started 3677 // as that's when the check is made (and yes, by its design...) 3678 func (s *DockerSuite) TestCmdCannotBeInvoked(c *testing.T) { 3679 expected := 126 3680 if testEnv.OSType == "windows" { 3681 expected = 127 3682 } 3683 name := "testCmdCannotBeInvoked" 3684 icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/etc").Assert(c, icmd.Expected{ 3685 ExitCode: expected, 3686 Error: fmt.Sprintf("exit status %d", expected), 3687 }) 3688 } 3689 3690 // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains 'Unable to find image' 3691 // FIXME(vdemeester) should be a unit test 3692 func (s *DockerSuite) TestRunNonExistingImage(c *testing.T) { 3693 icmd.RunCommand(dockerBinary, "run", "foo").Assert(c, icmd.Expected{ 3694 ExitCode: 125, 3695 Err: "Unable to find image", 3696 }) 3697 } 3698 3699 // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed 3700 // FIXME(vdemeester) should be a unit test 3701 func (s *DockerSuite) TestDockerFails(c *testing.T) { 3702 icmd.RunCommand(dockerBinary, "run", "-foo", "busybox").Assert(c, icmd.Expected{ 3703 ExitCode: 125, 3704 Error: "exit status 125", 3705 }) 3706 } 3707 3708 // TestRunInvalidReference invokes docker run with a bad reference. 3709 func (s *DockerSuite) TestRunInvalidReference(c *testing.T) { 3710 out, exit, _ := dockerCmdWithError("run", "busybox@foo") 3711 if exit == 0 { 3712 c.Fatalf("expected non-zero exist code; received %d", exit) 3713 } 3714 3715 if !strings.Contains(out, "invalid reference format") { 3716 c.Fatalf(`Expected "invalid reference format" in output; got: %s`, out) 3717 } 3718 } 3719 3720 // Test fix for issue #17854 3721 func (s *DockerSuite) TestRunInitLayerPathOwnership(c *testing.T) { 3722 // Not applicable on Windows as it does not support Linux uid/gid ownership 3723 testRequires(c, DaemonIsLinux) 3724 name := "testetcfileownership" 3725 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox 3726 RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd 3727 RUN echo 'dockerio:x:1001:' >> /etc/group 3728 RUN chown dockerio:dockerio /etc`)) 3729 3730 // Test that dockerio ownership of /etc is retained at runtime 3731 out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc") 3732 out = strings.TrimSpace(out) 3733 if out != "dockerio:dockerio" { 3734 c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out) 3735 } 3736 } 3737 3738 func (s *DockerSuite) TestRunWithOomScoreAdj(c *testing.T) { 3739 testRequires(c, DaemonIsLinux) 3740 3741 expected := "642" 3742 out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj") 3743 oomScoreAdj := strings.TrimSpace(out) 3744 if oomScoreAdj != "642" { 3745 c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj) 3746 } 3747 } 3748 3749 func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *testing.T) { 3750 testRequires(c, DaemonIsLinux) 3751 3752 out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true") 3753 assert.ErrorContains(c, err, "") 3754 expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]." 3755 if !strings.Contains(out, expected) { 3756 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 3757 } 3758 out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true") 3759 assert.ErrorContains(c, err, "") 3760 expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]." 3761 if !strings.Contains(out, expected) { 3762 c.Fatalf("Expected output to contain %q, got %q instead", expected, out) 3763 } 3764 } 3765 3766 func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *testing.T) { 3767 testRequires(c, DaemonIsLinux, NotUserNamespace) 3768 out, exitCode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile") 3769 assert.Assert(c, exitCode != 0) 3770 assert.Assert(c, strings.Contains(out, "invalid mount config")) 3771 } 3772 3773 func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *testing.T) { 3774 testRequires(c, DaemonIsLinux) 3775 3776 testImg := "testvolumecopy" 3777 buildImageSuccessfully(c, testImg, build.WithDockerfile(` 3778 FROM busybox 3779 RUN mkdir -p /foo && echo hello > /foo/hello 3780 `)) 3781 3782 dockerCmd(c, "run", "-v", "foo:/foo", testImg) 3783 out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello") 3784 assert.Equal(c, strings.TrimSpace(out), "hello") 3785 } 3786 3787 func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *testing.T) { 3788 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3789 3790 dockerCmd(c, "volume", "create", "test") 3791 3792 dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3793 dockerCmd(c, "volume", "inspect", "test") 3794 out, _ := dockerCmd(c, "volume", "ls", "-q") 3795 assert.Assert(c, strings.Contains(out, "test")) 3796 3797 dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3798 dockerCmd(c, "rm", "-fv", "test") 3799 dockerCmd(c, "volume", "inspect", "test") 3800 out, _ = dockerCmd(c, "volume", "ls", "-q") 3801 assert.Assert(c, strings.Contains(out, "test")) 3802 } 3803 3804 func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *testing.T) { 3805 prefix, _ := getPrefixAndSlashFromDaemonPlatform() 3806 3807 dockerCmd(c, "volume", "create", "test") 3808 cid, _ := dockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") 3809 dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") 3810 3811 cli, err := client.NewClientWithOpts(client.FromEnv) 3812 assert.NilError(c, err) 3813 defer cli.Close() 3814 3815 container, err := cli.ContainerInspect(context.Background(), strings.TrimSpace(cid)) 3816 assert.NilError(c, err) 3817 var vname string 3818 for _, v := range container.Mounts { 3819 if v.Name != "test" { 3820 vname = v.Name 3821 } 3822 } 3823 assert.Assert(c, vname != "") 3824 3825 // Remove the parent so there are not other references to the volumes 3826 dockerCmd(c, "rm", "-f", "parent") 3827 // now remove the child and ensure the named volume (and only the named volume) still exists 3828 dockerCmd(c, "rm", "-fv", "child") 3829 dockerCmd(c, "volume", "inspect", "test") 3830 out, _ := dockerCmd(c, "volume", "ls", "-q") 3831 assert.Assert(c, strings.Contains(out, "test")) 3832 assert.Assert(c, !strings.Contains(strings.TrimSpace(out), vname)) 3833 } 3834 3835 func (s *DockerSuite) TestRunAttachFailedNoLeak(c *testing.T) { 3836 nroutines, err := getGoroutineNumber() 3837 assert.NilError(c, err) 3838 3839 runSleepingContainer(c, "--name=test", "-p", "8000:8000") 3840 3841 // Wait until container is fully up and running 3842 assert.Assert(c, waitRun("test") == nil) 3843 3844 out, _, err := dockerCmdWithError("run", "--name=fail", "-p", "8000:8000", "busybox", "true") 3845 // We will need the following `inspect` to diagnose the issue if test fails (#21247) 3846 out1, err1 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "test") 3847 out2, err2 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "fail") 3848 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) 3849 // check for windows error as well 3850 // TODO Windows Post TP5. Fix the error message string 3851 outLowerCase := strings.ToLower(out) 3852 assert.Assert(c, strings.Contains(outLowerCase, "port is already allocated") || 3853 strings.Contains(outLowerCase, "were not connected because a duplicate name exists") || 3854 strings.Contains(outLowerCase, "the specified port already exists") || 3855 strings.Contains(outLowerCase, "hns failed with error : failed to create endpoint") || 3856 strings.Contains(outLowerCase, "hns failed with error : the object already exists"), fmt.Sprintf("Output: %s", out)) 3857 dockerCmd(c, "rm", "-f", "test") 3858 3859 // NGoroutines is not updated right away, so we need to wait before failing 3860 assert.Assert(c, waitForGoroutines(nroutines) == nil) 3861 } 3862 3863 // Test for one character directory name case (#20122) 3864 func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *testing.T) { 3865 testRequires(c, DaemonIsLinux) 3866 3867 out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo") 3868 assert.Equal(c, strings.TrimSpace(out), "/foo") 3869 } 3870 3871 func (s *DockerSuite) TestRunVolumeCopyFlag(c *testing.T) { 3872 testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume 3873 buildImageSuccessfully(c, "volumecopy", build.WithDockerfile(`FROM busybox 3874 RUN mkdir /foo && echo hello > /foo/bar 3875 CMD cat /foo/bar`)) 3876 dockerCmd(c, "volume", "create", "test") 3877 3878 // test with the nocopy flag 3879 out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy") 3880 assert.ErrorContains(c, err, "", out) 3881 // test default behavior which is to copy for non-binds 3882 out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") 3883 assert.Equal(c, strings.TrimSpace(out), "hello") 3884 // error out when the volume is already populated 3885 out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy") 3886 assert.ErrorContains(c, err, "", out) 3887 // do not error out when copy isn't explicitly set even though it's already populated 3888 out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") 3889 assert.Equal(c, strings.TrimSpace(out), "hello") 3890 3891 // do not allow copy modes on volumes-from 3892 dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") 3893 out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true") 3894 assert.ErrorContains(c, err, "", out) 3895 out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true") 3896 assert.ErrorContains(c, err, "", out) 3897 3898 // do not allow copy modes on binds 3899 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true") 3900 assert.ErrorContains(c, err, "", out) 3901 out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true") 3902 assert.ErrorContains(c, err, "", out) 3903 } 3904 3905 // Test case for #21976 3906 func (s *DockerSuite) TestRunDNSInHostMode(c *testing.T) { 3907 testRequires(c, DaemonIsLinux, NotUserNamespace) 3908 3909 expectedOutput := "nameserver 127.0.0.1" 3910 expectedWarning := "Localhost DNS setting" 3911 cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3912 Out: expectedOutput, 3913 Err: expectedWarning, 3914 }) 3915 3916 expectedOutput = "nameserver 1.2.3.4" 3917 cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3918 Out: expectedOutput, 3919 }) 3920 3921 expectedOutput = "search example.com" 3922 cli.DockerCmd(c, "run", "--dns-search=example.com", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3923 Out: expectedOutput, 3924 }) 3925 3926 expectedOutput = "options timeout:3" 3927 cli.DockerCmd(c, "run", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{ 3928 Out: expectedOutput, 3929 }) 3930 3931 expectedOutput1 := "nameserver 1.2.3.4" 3932 expectedOutput2 := "search example.com" 3933 expectedOutput3 := "options timeout:3" 3934 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() 3935 assert.Assert(c, strings.Contains(out, expectedOutput1), "Expected '%s', but got %q", expectedOutput1, out) 3936 assert.Assert(c, strings.Contains(out, expectedOutput2), "Expected '%s', but got %q", expectedOutput2, out) 3937 assert.Assert(c, strings.Contains(out, expectedOutput3), "Expected '%s', but got %q", expectedOutput3, out) 3938 } 3939 3940 // Test case for #21976 3941 func (s *DockerSuite) TestRunAddHostInHostMode(c *testing.T) { 3942 testRequires(c, DaemonIsLinux, NotUserNamespace) 3943 3944 expectedOutput := "1.2.3.4\textra" 3945 out, _ := dockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts") 3946 assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out) 3947 } 3948 3949 func (s *DockerSuite) TestRunRmAndWait(c *testing.T) { 3950 dockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2") 3951 3952 out, code, err := dockerCmdWithError("wait", "test") 3953 assert.Assert(c, err == nil, "out: %s; exit code: %d", out, code) 3954 assert.Equal(c, out, "2\n", "exit code: %d", code) 3955 assert.Equal(c, code, 0) 3956 } 3957 3958 // Test that auto-remove is performed by the daemon (API 1.25 and above) 3959 func (s *DockerSuite) TestRunRm(c *testing.T) { 3960 name := "miss-me-when-im-gone" 3961 cli.DockerCmd(c, "run", "--name="+name, "--rm", "busybox") 3962 3963 cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{ 3964 ExitCode: 1, 3965 Err: "No such object: " + name, 3966 }) 3967 } 3968 3969 // Test that auto-remove is performed by the client on API versions that do not support daemon-side api-remove (API < 1.25) 3970 func (s *DockerSuite) TestRunRmPre125Api(c *testing.T) { 3971 name := "miss-me-when-im-gone" 3972 envs := appendBaseEnv(os.Getenv("DOCKER_TLS_VERIFY") != "", "DOCKER_API_VERSION=1.24") 3973 cli.Docker(cli.Args("run", "--name="+name, "--rm", "busybox"), cli.WithEnvironmentVariables(envs...)).Assert(c, icmd.Success) 3974 3975 cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{ 3976 ExitCode: 1, 3977 Err: "No such object: " + name, 3978 }) 3979 } 3980 3981 // Test case for #23498 3982 func (s *DockerSuite) TestRunUnsetEntrypoint(c *testing.T) { 3983 testRequires(c, DaemonIsLinux) 3984 name := "test-entrypoint" 3985 dockerfile := `FROM busybox 3986 ADD entrypoint.sh /entrypoint.sh 3987 RUN chmod 755 /entrypoint.sh 3988 ENTRYPOINT ["/entrypoint.sh"] 3989 CMD echo foobar` 3990 3991 ctx := fakecontext.New(c, "", 3992 fakecontext.WithDockerfile(dockerfile), 3993 fakecontext.WithFiles(map[string]string{ 3994 "entrypoint.sh": `#!/bin/sh 3995 echo "I am an entrypoint" 3996 exec "$@"`, 3997 })) 3998 defer ctx.Close() 3999 4000 cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) 4001 4002 out := cli.DockerCmd(c, "run", "--entrypoint=", "-t", name, "echo", "foo").Combined() 4003 assert.Equal(c, strings.TrimSpace(out), "foo") 4004 4005 // CMD will be reset as well (the same as setting a custom entrypoint) 4006 cli.Docker(cli.Args("run", "--entrypoint=", "-t", name)).Assert(c, icmd.Expected{ 4007 ExitCode: 125, 4008 Err: "No command specified", 4009 }) 4010 } 4011 4012 func (s *DockerDaemonSuite) TestRunWithUlimitAndDaemonDefault(c *testing.T) { 4013 s.d.StartWithBusybox(c, "--debug", "--default-ulimit=nofile=65535") 4014 4015 name := "test-A" 4016 _, err := s.d.Cmd("run", "--name", name, "-d", "busybox", "top") 4017 assert.NilError(c, err) 4018 assert.NilError(c, s.d.WaitRun(name)) 4019 4020 out, err := s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) 4021 assert.NilError(c, err) 4022 assert.Assert(c, strings.Contains(out, "[nofile=65535:65535]")) 4023 name = "test-B" 4024 _, err = s.d.Cmd("run", "--name", name, "--ulimit=nofile=42", "-d", "busybox", "top") 4025 assert.NilError(c, err) 4026 assert.NilError(c, s.d.WaitRun(name)) 4027 4028 out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) 4029 assert.NilError(c, err) 4030 assert.Assert(c, strings.Contains(out, "[nofile=42:42]")) 4031 } 4032 4033 func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *testing.T) { 4034 nroutines, err := getGoroutineNumber() 4035 assert.NilError(c, err) 4036 4037 out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true") 4038 assert.ErrorContains(c, err, "") 4039 assert.Assert(c, strings.Contains(out, "failed to initialize logging driver"), "error should be about logging driver, got output %s", out) 4040 // NGoroutines is not updated right away, so we need to wait before failing 4041 assert.Assert(c, waitForGoroutines(nroutines) == nil) 4042 } 4043 4044 // Handles error conditions for --credentialspec. Validating E2E success cases 4045 // requires additional infrastructure (AD for example) on CI servers. 4046 func (s *DockerSuite) TestRunCredentialSpecFailures(c *testing.T) { 4047 testRequires(c, DaemonIsWindows) 4048 4049 attempts := []struct{ value, expectedError string }{ 4050 {"rubbish", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4051 {"rubbish://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4052 {"file://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4053 {"registry://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"}, 4054 {`file://c:\blah.txt`, "path cannot be absolute"}, 4055 {`file://doesnotexist.txt`, "The system cannot find the file specified"}, 4056 } 4057 for _, attempt := range attempts { 4058 _, _, err := dockerCmdWithError("run", "--security-opt=credentialspec="+attempt.value, "busybox", "true") 4059 assert.Assert(c, err != nil, "%s expected non-nil err", attempt.value) 4060 assert.Assert(c, strings.Contains(err.Error(), attempt.expectedError), "%s expected %s got %s", attempt.value, attempt.expectedError, err) 4061 } 4062 } 4063 4064 // Windows specific test to validate credential specs with a well-formed spec. 4065 func (s *DockerSuite) TestRunCredentialSpecWellFormed(c *testing.T) { 4066 testRequires(c, DaemonIsWindows, testEnv.IsLocalDaemon) 4067 4068 validCredSpecs := readFile(`fixtures\credentialspecs\valid.json`, c) 4069 writeFile(filepath.Join(testEnv.DaemonInfo.DockerRootDir, `credentialspecs\valid.json`), validCredSpecs, c) 4070 4071 for _, value := range []string{"file://valid.json", "raw://" + validCredSpecs} { 4072 // `nltest /PARENTDOMAIN` simply reads the local config, and does not require having an AD 4073 // controller handy 4074 out, _ := dockerCmd(c, "run", "--rm", "--security-opt=credentialspec="+value, minimalBaseImage(), "nltest", "/PARENTDOMAIN") 4075 4076 assert.Assert(c, strings.Contains(out, "hyperv.local.")) 4077 assert.Assert(c, strings.Contains(out, "The command completed successfully")) 4078 } 4079 } 4080 4081 func (s *DockerSuite) TestRunDuplicateMount(c *testing.T) { 4082 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 4083 4084 tmpFile, err := ioutil.TempFile("", "touch-me") 4085 assert.NilError(c, err) 4086 defer tmpFile.Close() 4087 4088 data := "touch-me-foo-bar\n" 4089 if _, err := tmpFile.Write([]byte(data)); err != nil { 4090 c.Fatal(err) 4091 } 4092 4093 name := "test" 4094 out, _ := dockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /") 4095 assert.Assert(c, !strings.Contains(out, "tmp:")) 4096 assert.Assert(c, strings.Contains(out, data)) 4097 out = inspectFieldJSON(c, name, "Config.Volumes") 4098 assert.Assert(c, strings.Contains(out, "null")) 4099 } 4100 4101 func (s *DockerSuite) TestRunWindowsWithCPUCount(c *testing.T) { 4102 testRequires(c, DaemonIsWindows) 4103 4104 out, _ := dockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing") 4105 assert.Equal(c, strings.TrimSpace(out), "testing") 4106 4107 out = inspectField(c, "test", "HostConfig.CPUCount") 4108 assert.Equal(c, out, "1") 4109 } 4110 4111 func (s *DockerSuite) TestRunWindowsWithCPUShares(c *testing.T) { 4112 testRequires(c, DaemonIsWindows) 4113 4114 out, _ := dockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing") 4115 assert.Equal(c, strings.TrimSpace(out), "testing") 4116 4117 out = inspectField(c, "test", "HostConfig.CPUShares") 4118 assert.Equal(c, out, "1000") 4119 } 4120 4121 func (s *DockerSuite) TestRunWindowsWithCPUPercent(c *testing.T) { 4122 testRequires(c, DaemonIsWindows) 4123 4124 out, _ := dockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") 4125 assert.Equal(c, strings.TrimSpace(out), "testing") 4126 4127 out = inspectField(c, "test", "HostConfig.CPUPercent") 4128 assert.Equal(c, out, "80") 4129 } 4130 4131 func (s *DockerSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) { 4132 testRequires(c, IsolationIsProcess) 4133 4134 out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") 4135 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")) 4136 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")) 4137 assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing")) 4138 out = inspectField(c, "test", "HostConfig.CPUCount") 4139 assert.Equal(c, out, "1") 4140 4141 out = inspectField(c, "test", "HostConfig.CPUShares") 4142 assert.Equal(c, out, "0") 4143 4144 out = inspectField(c, "test", "HostConfig.CPUPercent") 4145 assert.Equal(c, out, "0") 4146 } 4147 4148 func (s *DockerSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) { 4149 testRequires(c, IsolationIsHyperv) 4150 4151 out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") 4152 assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing")) 4153 out = inspectField(c, "test", "HostConfig.CPUCount") 4154 assert.Equal(c, out, "1") 4155 4156 out = inspectField(c, "test", "HostConfig.CPUShares") 4157 assert.Equal(c, out, "1000") 4158 4159 out = inspectField(c, "test", "HostConfig.CPUPercent") 4160 assert.Equal(c, out, "80") 4161 } 4162 4163 // Test for #25099 4164 func (s *DockerSuite) TestRunEmptyEnv(c *testing.T) { 4165 testRequires(c, DaemonIsLinux) 4166 4167 expectedOutput := "invalid environment variable:" 4168 4169 out, _, err := dockerCmdWithError("run", "-e", "", "busybox", "true") 4170 assert.ErrorContains(c, err, "") 4171 assert.Assert(c, strings.Contains(out, expectedOutput)) 4172 4173 out, _, err = dockerCmdWithError("run", "-e", "=", "busybox", "true") 4174 assert.ErrorContains(c, err, "") 4175 assert.Assert(c, strings.Contains(out, expectedOutput)) 4176 4177 out, _, err = dockerCmdWithError("run", "-e", "=foo", "busybox", "true") 4178 assert.ErrorContains(c, err, "") 4179 assert.Assert(c, strings.Contains(out, expectedOutput)) 4180 } 4181 4182 // #28658 4183 func (s *DockerSuite) TestSlowStdinClosing(c *testing.T) { 4184 name := "testslowstdinclosing" 4185 repeat := 3 // regression happened 50% of the time 4186 for i := 0; i < repeat; i++ { 4187 cmd := icmd.Cmd{ 4188 Command: []string{dockerBinary, "run", "--rm", "--name", name, "-i", "busybox", "cat"}, 4189 Stdin: &delayedReader{}, 4190 } 4191 done := make(chan error, 1) 4192 go func() { 4193 err := icmd.RunCmd(cmd).Error 4194 done <- err 4195 }() 4196 4197 select { 4198 case <-time.After(30 * time.Second): 4199 c.Fatal("running container timed out") // cleanup in teardown 4200 case err := <-done: 4201 assert.NilError(c, err) 4202 } 4203 } 4204 } 4205 4206 type delayedReader struct{} 4207 4208 func (s *delayedReader) Read([]byte) (int, error) { 4209 time.Sleep(500 * time.Millisecond) 4210 return 0, io.EOF 4211 } 4212 4213 // #28823 (originally #28639) 4214 func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *testing.T) { 4215 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) 4216 emptyDir, err := ioutil.TempDir("", "test-read-only-dev-shm") 4217 assert.NilError(c, err) 4218 defer os.RemoveAll(emptyDir) 4219 out, _, err := dockerCmdWithError("run", "--rm", "--read-only", 4220 "-v", fmt.Sprintf("%s:/dev/shm:ro", emptyDir), 4221 "busybox", "touch", "/dev/shm/foo") 4222 assert.ErrorContains(c, err, "", out) 4223 assert.Assert(c, strings.Contains(out, "Read-only file system")) 4224 } 4225 4226 func (s *DockerSuite) TestRunMount(c *testing.T) { 4227 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) 4228 4229 // mnt1, mnt2, and testCatFooBar are commonly used in multiple test cases 4230 tmpDir, err := ioutil.TempDir("", "mount") 4231 if err != nil { 4232 c.Fatal(err) 4233 } 4234 defer os.RemoveAll(tmpDir) 4235 mnt1, mnt2 := path.Join(tmpDir, "mnt1"), path.Join(tmpDir, "mnt2") 4236 if err := os.Mkdir(mnt1, 0755); err != nil { 4237 c.Fatal(err) 4238 } 4239 if err := os.Mkdir(mnt2, 0755); err != nil { 4240 c.Fatal(err) 4241 } 4242 if err := ioutil.WriteFile(path.Join(mnt1, "test1"), []byte("test1"), 0644); err != nil { 4243 c.Fatal(err) 4244 } 4245 if err := ioutil.WriteFile(path.Join(mnt2, "test2"), []byte("test2"), 0644); err != nil { 4246 c.Fatal(err) 4247 } 4248 testCatFooBar := func(cName string) error { 4249 out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1") 4250 if out != "test1" { 4251 return fmt.Errorf("%s not mounted on /foo", mnt1) 4252 } 4253 out, _ = dockerCmd(c, "exec", cName, "cat", "/bar/test2") 4254 if out != "test2" { 4255 return fmt.Errorf("%s not mounted on /bar", mnt2) 4256 } 4257 return nil 4258 } 4259 4260 type testCase struct { 4261 equivalents [][]string 4262 valid bool 4263 // fn should be nil if valid==false 4264 fn func(cName string) error 4265 } 4266 cases := []testCase{ 4267 { 4268 equivalents: [][]string{ 4269 { 4270 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4271 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/bar", mnt2), 4272 }, 4273 { 4274 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4275 "--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2), 4276 }, 4277 { 4278 "--volume", mnt1 + ":/foo", 4279 "--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2), 4280 }, 4281 }, 4282 valid: true, 4283 fn: testCatFooBar, 4284 }, 4285 { 4286 equivalents: [][]string{ 4287 { 4288 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1), 4289 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2), 4290 }, 4291 { 4292 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1), 4293 "--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2), 4294 }, 4295 }, 4296 valid: false, 4297 }, 4298 { 4299 equivalents: [][]string{ 4300 { 4301 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4302 "--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2), 4303 }, 4304 { 4305 "--volume", mnt1 + ":/foo", 4306 "--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2), 4307 }, 4308 }, 4309 valid: false, 4310 fn: testCatFooBar, 4311 }, 4312 { 4313 equivalents: [][]string{ 4314 { 4315 "--read-only", 4316 "--mount", "type=volume,dst=/bar", 4317 }, 4318 }, 4319 valid: true, 4320 fn: func(cName string) error { 4321 _, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere") 4322 return err 4323 }, 4324 }, 4325 { 4326 equivalents: [][]string{ 4327 { 4328 "--read-only", 4329 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4330 "--mount", "type=volume,dst=/bar", 4331 }, 4332 { 4333 "--read-only", 4334 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4335 "--mount", "type=volume,dst=/bar", 4336 }, 4337 }, 4338 valid: true, 4339 fn: func(cName string) error { 4340 out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1") 4341 if out != "test1" { 4342 return fmt.Errorf("%s not mounted on /foo", mnt1) 4343 } 4344 _, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere") 4345 return err 4346 }, 4347 }, 4348 { 4349 equivalents: [][]string{ 4350 { 4351 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4352 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt2), 4353 }, 4354 { 4355 "--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1), 4356 "--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2), 4357 }, 4358 { 4359 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4360 "--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2), 4361 }, 4362 }, 4363 valid: false, 4364 }, 4365 { 4366 equivalents: [][]string{ 4367 { 4368 "--volume", fmt.Sprintf("%s:/foo", mnt1), 4369 "--mount", fmt.Sprintf("type=volume,src=%s,target=/foo", mnt2), 4370 }, 4371 }, 4372 valid: false, 4373 }, 4374 { 4375 equivalents: [][]string{ 4376 { 4377 "--mount", "type=volume,target=/foo", 4378 "--mount", "type=volume,target=/foo", 4379 }, 4380 }, 4381 valid: false, 4382 }, 4383 } 4384 4385 for i, testCase := range cases { 4386 for j, opts := range testCase.equivalents { 4387 cName := fmt.Sprintf("mount-%d-%d", i, j) 4388 _, _, err := dockerCmdWithError(append([]string{"run", "-i", "-d", "--name", cName}, 4389 append(opts, []string{"busybox", "top"}...)...)...) 4390 if testCase.valid { 4391 assert.Assert(c, err == nil, "got error while creating a container with %v (%s)", opts, cName) 4392 assert.Assert(c, testCase.fn(cName) == nil, "got error while executing test for %v (%s)", opts, cName) 4393 dockerCmd(c, "rm", "-f", cName) 4394 } else { 4395 assert.Assert(c, err != nil, "got nil while creating a container with %v (%s)", opts, cName) 4396 } 4397 } 4398 } 4399 } 4400 4401 // Test that passing a FQDN as hostname properly sets hostname, and 4402 // /etc/hostname. Test case for 29100 4403 func (s *DockerSuite) TestRunHostnameFQDN(c *testing.T) { 4404 testRequires(c, DaemonIsLinux) 4405 4406 expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com" 4407 out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`) 4408 assert.Equal(c, strings.TrimSpace(out), expectedOutput) 4409 4410 out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`) 4411 expectedOutput = "foobar.example.com foobar" 4412 assert.Assert(c, strings.Contains(strings.TrimSpace(out), expectedOutput)) 4413 } 4414 4415 // Test case for 29129 4416 func (s *DockerSuite) TestRunHostnameInHostMode(c *testing.T) { 4417 testRequires(c, DaemonIsLinux, NotUserNamespace) 4418 4419 expectedOutput := "foobar\nfoobar" 4420 out, _ := dockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`) 4421 assert.Equal(c, strings.TrimSpace(out), expectedOutput) 4422 } 4423 4424 func (s *DockerSuite) TestRunAddDeviceCgroupRule(c *testing.T) { 4425 testRequires(c, DaemonIsLinux) 4426 4427 deviceRule := "c 7:128 rwm" 4428 4429 out, _ := dockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list") 4430 if strings.Contains(out, deviceRule) { 4431 c.Fatalf("%s shouldn't been in the device.list", deviceRule) 4432 } 4433 4434 out, _ = dockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list") 4435 assert.Equal(c, strings.TrimSpace(out), deviceRule) 4436 } 4437 4438 // Verifies that running as local system is operating correctly on Windows 4439 func (s *DockerSuite) TestWindowsRunAsSystem(c *testing.T) { 4440 testRequires(c, DaemonIsWindowsAtLeastBuild(osversion.RS3)) 4441 out, _ := dockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`) 4442 assert.Equal(c, strings.TrimSpace(out), "XYZZY$") 4443 }