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