github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/integration-cli/docker_cli_daemon_test.go (about) 1 // +build linux 2 3 package main 4 5 import ( 6 "bufio" 7 "bytes" 8 "encoding/json" 9 "fmt" 10 "io" 11 "io/ioutil" 12 "net" 13 "os" 14 "os/exec" 15 "path" 16 "path/filepath" 17 "regexp" 18 "strconv" 19 "strings" 20 "sync" 21 "syscall" 22 "time" 23 24 "github.com/docker/docker/integration-cli/checker" 25 "github.com/docker/docker/integration-cli/daemon" 26 "github.com/docker/docker/pkg/mount" 27 "github.com/docker/docker/pkg/stringid" 28 "github.com/docker/docker/pkg/testutil" 29 icmd "github.com/docker/docker/pkg/testutil/cmd" 30 units "github.com/docker/go-units" 31 "github.com/docker/libnetwork/iptables" 32 "github.com/docker/libtrust" 33 "github.com/go-check/check" 34 "github.com/kr/pty" 35 ) 36 37 // TestLegacyDaemonCommand test starting docker daemon using "deprecated" docker daemon 38 // command. Remove this test when we remove this. 39 func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *check.C) { 40 cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug") 41 err := cmd.Start() 42 c.Assert(err, checker.IsNil, check.Commentf("could not start daemon using 'docker daemon'")) 43 44 c.Assert(cmd.Process.Kill(), checker.IsNil) 45 } 46 47 func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { 48 s.d.StartWithBusybox(c) 49 50 if out, err := s.d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil { 51 c.Fatalf("Could not run top1: err=%v\n%s", err, out) 52 } 53 // --restart=no by default 54 if out, err := s.d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil { 55 c.Fatalf("Could not run top2: err=%v\n%s", err, out) 56 } 57 58 testRun := func(m map[string]bool, prefix string) { 59 var format string 60 for cont, shouldRun := range m { 61 out, err := s.d.Cmd("ps") 62 if err != nil { 63 c.Fatalf("Could not run ps: err=%v\n%q", err, out) 64 } 65 if shouldRun { 66 format = "%scontainer %q is not running" 67 } else { 68 format = "%scontainer %q is running" 69 } 70 if shouldRun != strings.Contains(out, cont) { 71 c.Fatalf(format, prefix, cont) 72 } 73 } 74 } 75 76 testRun(map[string]bool{"top1": true, "top2": true}, "") 77 78 s.d.Restart(c) 79 testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") 80 } 81 82 func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { 83 s.d.StartWithBusybox(c) 84 85 if out, err := s.d.Cmd("run", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil { 86 c.Fatal(err, out) 87 } 88 89 s.d.Restart(c) 90 91 if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil { 92 c.Fatal(err) 93 } 94 95 if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil { 96 c.Fatal(err, out) 97 } 98 99 out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1") 100 c.Assert(err, check.IsNil) 101 102 if _, err := inspectMountPointJSON(out, "/foo"); err != nil { 103 c.Fatalf("Expected volume to exist: /foo, error: %v\n", err) 104 } 105 } 106 107 // #11008 108 func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) { 109 s.d.StartWithBusybox(c) 110 111 out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top") 112 c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out)) 113 114 out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top") 115 c.Assert(err, check.IsNil, check.Commentf("run top2: %v", out)) 116 117 testRun := func(m map[string]bool, prefix string) { 118 var format string 119 for name, shouldRun := range m { 120 out, err := s.d.Cmd("ps") 121 c.Assert(err, check.IsNil, check.Commentf("run ps: %v", out)) 122 if shouldRun { 123 format = "%scontainer %q is not running" 124 } else { 125 format = "%scontainer %q is running" 126 } 127 c.Assert(strings.Contains(out, name), check.Equals, shouldRun, check.Commentf(format, prefix, name)) 128 } 129 } 130 131 // both running 132 testRun(map[string]bool{"top1": true, "top2": true}, "") 133 134 out, err = s.d.Cmd("stop", "top1") 135 c.Assert(err, check.IsNil, check.Commentf(out)) 136 137 out, err = s.d.Cmd("stop", "top2") 138 c.Assert(err, check.IsNil, check.Commentf(out)) 139 140 // both stopped 141 testRun(map[string]bool{"top1": false, "top2": false}, "") 142 143 s.d.Restart(c) 144 145 // restart=always running 146 testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") 147 148 out, err = s.d.Cmd("start", "top2") 149 c.Assert(err, check.IsNil, check.Commentf("start top2: %v", out)) 150 151 s.d.Restart(c) 152 153 // both running 154 testRun(map[string]bool{"top1": true, "top2": true}, "After second daemon restart: ") 155 156 } 157 158 func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *check.C) { 159 s.d.StartWithBusybox(c) 160 161 out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false") 162 c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out)) 163 164 // wait test1 to stop 165 hostArgs := []string{"--host", s.d.Sock()} 166 err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...) 167 c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not")) 168 169 // record last start time 170 out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") 171 c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) 172 lastStartTime := out 173 174 s.d.Restart(c) 175 176 // test1 shouldn't restart at all 177 err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...) 178 c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not")) 179 180 // make sure test1 isn't restarted when daemon restart 181 // if "StartAt" time updates, means test1 was once restarted. 182 out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") 183 c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) 184 c.Assert(out, checker.Equals, lastStartTime, check.Commentf("test1 shouldn't start after daemon restarts")) 185 } 186 187 func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) { 188 s.d.Start(c, "--iptables=false") 189 } 190 191 // Make sure we cannot shrink base device at daemon restart. 192 func (s *DockerDaemonSuite) TestDaemonRestartWithInvalidBasesize(c *check.C) { 193 testRequires(c, Devicemapper) 194 s.d.Start(c) 195 196 oldBasesizeBytes := s.d.GetBaseDeviceSize(c) 197 var newBasesizeBytes int64 = 1073741824 //1GB in bytes 198 199 if newBasesizeBytes < oldBasesizeBytes { 200 err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) 201 c.Assert(err, check.IsNil, check.Commentf("daemon should not have started as new base device size is less than existing base device size: %v", err)) 202 } 203 s.d.Stop(c) 204 } 205 206 // Make sure we can grow base device at daemon restart. 207 func (s *DockerDaemonSuite) TestDaemonRestartWithIncreasedBasesize(c *check.C) { 208 testRequires(c, Devicemapper) 209 s.d.Start(c) 210 211 oldBasesizeBytes := s.d.GetBaseDeviceSize(c) 212 213 var newBasesizeBytes int64 = 53687091200 //50GB in bytes 214 215 if newBasesizeBytes < oldBasesizeBytes { 216 c.Skip(fmt.Sprintf("New base device size (%v) must be greater than (%s)", units.HumanSize(float64(newBasesizeBytes)), units.HumanSize(float64(oldBasesizeBytes)))) 217 } 218 219 err := s.d.RestartWithError("--storage-opt", fmt.Sprintf("dm.basesize=%d", newBasesizeBytes)) 220 c.Assert(err, check.IsNil, check.Commentf("we should have been able to start the daemon with increased base device size: %v", err)) 221 222 basesizeAfterRestart := s.d.GetBaseDeviceSize(c) 223 newBasesize, err := convertBasesize(newBasesizeBytes) 224 c.Assert(err, check.IsNil, check.Commentf("Error in converting base device size: %v", err)) 225 c.Assert(newBasesize, check.Equals, basesizeAfterRestart, check.Commentf("Basesize passed is not equal to Basesize set")) 226 s.d.Stop(c) 227 } 228 229 func convertBasesize(basesizeBytes int64) (int64, error) { 230 basesize := units.HumanSize(float64(basesizeBytes)) 231 basesize = strings.Trim(basesize, " ")[:len(basesize)-3] 232 basesizeFloat, err := strconv.ParseFloat(strings.Trim(basesize, " "), 64) 233 if err != nil { 234 return 0, err 235 } 236 return int64(basesizeFloat) * 1024 * 1024 * 1024, nil 237 } 238 239 // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and 240 // no longer has an IP associated, we should gracefully handle that case and associate 241 // an IP with it rather than fail daemon start 242 func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) { 243 // rather than depending on brctl commands to verify docker0 is created and up 244 // let's start the daemon and stop it, and then make a modification to run the 245 // actual test 246 s.d.Start(c) 247 s.d.Stop(c) 248 249 // now we will remove the ip from docker0 and then try starting the daemon 250 icmd.RunCommand("ip", "addr", "flush", "dev", "docker0").Assert(c, icmd.Success) 251 252 if err := s.d.StartWithError(); err != nil { 253 warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix" 254 c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning) 255 } 256 } 257 258 func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) { 259 s.d.StartWithBusybox(c) 260 261 if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { 262 c.Fatalf("Could not run top: %s, %v", out, err) 263 } 264 265 ipTablesSearchString := "tcp dpt:80" 266 267 // get output from iptables with container running 268 verifyIPTablesContains(c, ipTablesSearchString) 269 270 s.d.Stop(c) 271 272 // get output from iptables after restart 273 verifyIPTablesDoesNotContains(c, ipTablesSearchString) 274 } 275 276 func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) { 277 s.d.StartWithBusybox(c) 278 279 if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil { 280 c.Fatalf("Could not run top: %s, %v", out, err) 281 } 282 283 // get output from iptables with container running 284 ipTablesSearchString := "tcp dpt:80" 285 verifyIPTablesContains(c, ipTablesSearchString) 286 287 s.d.Restart(c) 288 289 // make sure the container is not running 290 runningOut, err := s.d.Cmd("inspect", "--format={{.State.Running}}", "top") 291 if err != nil { 292 c.Fatalf("Could not inspect on container: %s, %v", runningOut, err) 293 } 294 if strings.TrimSpace(runningOut) != "true" { 295 c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut)) 296 } 297 298 // get output from iptables after restart 299 verifyIPTablesContains(c, ipTablesSearchString) 300 } 301 302 func verifyIPTablesContains(c *check.C, ipTablesSearchString string) { 303 result := icmd.RunCommand("iptables", "-nvL") 304 result.Assert(c, icmd.Success) 305 if !strings.Contains(result.Combined(), ipTablesSearchString) { 306 c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, result.Combined()) 307 } 308 } 309 310 func verifyIPTablesDoesNotContains(c *check.C, ipTablesSearchString string) { 311 result := icmd.RunCommand("iptables", "-nvL") 312 result.Assert(c, icmd.Success) 313 if strings.Contains(result.Combined(), ipTablesSearchString) { 314 c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, result.Combined()) 315 } 316 } 317 318 // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge 319 // has the fe80::1 address and that a container is assigned a link-local address 320 func (s *DockerDaemonSuite) TestDaemonIPv6Enabled(c *check.C) { 321 testRequires(c, IPv6) 322 323 setupV6(c) 324 defer teardownV6(c) 325 326 s.d.StartWithBusybox(c, "--ipv6") 327 328 iface, err := net.InterfaceByName("docker0") 329 if err != nil { 330 c.Fatalf("Error getting docker0 interface: %v", err) 331 } 332 333 addrs, err := iface.Addrs() 334 if err != nil { 335 c.Fatalf("Error getting addresses for docker0 interface: %v", err) 336 } 337 338 var found bool 339 expected := "fe80::1/64" 340 341 for i := range addrs { 342 if addrs[i].String() == expected { 343 found = true 344 break 345 } 346 } 347 348 if !found { 349 c.Fatalf("Bridge does not have an IPv6 Address") 350 } 351 352 if out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil { 353 c.Fatalf("Could not run container: %s, %v", out, err) 354 } 355 356 out, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.LinkLocalIPv6Address}}'", "ipv6test") 357 out = strings.Trim(out, " \r\n'") 358 359 if err != nil { 360 c.Fatalf("Error inspecting container: %s, %v", out, err) 361 } 362 363 if ip := net.ParseIP(out); ip == nil { 364 c.Fatalf("Container should have a link-local IPv6 address") 365 } 366 367 out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}'", "ipv6test") 368 out = strings.Trim(out, " \r\n'") 369 370 if err != nil { 371 c.Fatalf("Error inspecting container: %s, %v", out, err) 372 } 373 374 if ip := net.ParseIP(out); ip != nil { 375 c.Fatalf("Container should not have a global IPv6 address: %v", out) 376 } 377 } 378 379 // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR 380 // that running containers are given a link-local and global IPv6 address 381 func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) { 382 // IPv6 setup is messing with local bridge address. 383 testRequires(c, SameHostDaemon) 384 // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with 385 // ipv6 enabled 386 deleteInterface(c, "docker0") 387 388 s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64", "--default-gateway-v6=2001:db8:2::100") 389 390 out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest") 391 c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err)) 392 393 out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") 394 out = strings.Trim(out, " \r\n'") 395 396 c.Assert(err, checker.IsNil, check.Commentf(out)) 397 398 ip := net.ParseIP(out) 399 c.Assert(ip, checker.NotNil, check.Commentf("Container should have a global IPv6 address")) 400 401 out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.IPv6Gateway}}", "ipv6test") 402 c.Assert(err, checker.IsNil, check.Commentf(out)) 403 404 c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:2::100", check.Commentf("Container should have a global IPv6 gateway")) 405 } 406 407 // TestDaemonIPv6FixedCIDRAndMac checks that when the daemon is started with ipv6 fixed CIDR 408 // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR 409 func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) { 410 // IPv6 setup is messing with local bridge address. 411 testRequires(c, SameHostDaemon) 412 // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with 413 // ipv6 enabled 414 deleteInterface(c, "docker0") 415 416 s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64") 417 418 out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox") 419 c.Assert(err, checker.IsNil) 420 421 out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") 422 c.Assert(err, checker.IsNil) 423 c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff") 424 } 425 426 func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) { 427 c.Assert(s.d.StartWithError("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level")) 428 } 429 430 func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) { 431 s.d.Start(c, "--log-level=debug") 432 content, err := s.d.ReadLogFile() 433 c.Assert(err, checker.IsNil) 434 if !strings.Contains(string(content), `level=debug`) { 435 c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content)) 436 } 437 } 438 439 func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) { 440 // we creating new daemons to create new logFile 441 s.d.Start(c, "--log-level=fatal") 442 content, err := s.d.ReadLogFile() 443 c.Assert(err, checker.IsNil) 444 if strings.Contains(string(content), `level=debug`) { 445 c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content)) 446 } 447 } 448 449 func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { 450 s.d.Start(c, "-D") 451 content, err := s.d.ReadLogFile() 452 c.Assert(err, checker.IsNil) 453 if !strings.Contains(string(content), `level=debug`) { 454 c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content)) 455 } 456 } 457 458 func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { 459 s.d.Start(c, "--debug") 460 content, err := s.d.ReadLogFile() 461 c.Assert(err, checker.IsNil) 462 if !strings.Contains(string(content), `level=debug`) { 463 c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content)) 464 } 465 } 466 467 func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) { 468 s.d.Start(c, "--debug", "--log-level=fatal") 469 content, err := s.d.ReadLogFile() 470 c.Assert(err, checker.IsNil) 471 if !strings.Contains(string(content), `level=debug`) { 472 c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) 473 } 474 } 475 476 func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) { 477 listeningPorts := [][]string{ 478 {"0.0.0.0", "0.0.0.0", "5678"}, 479 {"127.0.0.1", "127.0.0.1", "1234"}, 480 {"localhost", "127.0.0.1", "1235"}, 481 } 482 483 cmdArgs := make([]string, 0, len(listeningPorts)*2) 484 for _, hostDirective := range listeningPorts { 485 cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2])) 486 } 487 488 s.d.StartWithBusybox(c, cmdArgs...) 489 490 for _, hostDirective := range listeningPorts { 491 output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true") 492 if err == nil { 493 c.Fatalf("Container should not start, expected port already allocated error: %q", output) 494 } else if !strings.Contains(output, "port is already allocated") { 495 c.Fatalf("Expected port is already allocated error: %q", output) 496 } 497 } 498 } 499 500 func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) { 501 // TODO: skip or update for Windows daemon 502 os.Remove("/etc/docker/key.json") 503 s.d.Start(c) 504 s.d.Stop(c) 505 506 k, err := libtrust.LoadKeyFile("/etc/docker/key.json") 507 if err != nil { 508 c.Fatalf("Error opening key file") 509 } 510 kid := k.KeyID() 511 // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF) 512 if len(kid) != 59 { 513 c.Fatalf("Bad key ID: %s", kid) 514 } 515 } 516 517 func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) { 518 // TODO: skip or update for Windows daemon 519 os.Remove("/etc/docker/key.json") 520 k1, err := libtrust.GenerateECP256PrivateKey() 521 if err != nil { 522 c.Fatalf("Error generating private key: %s", err) 523 } 524 if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".docker"), 0755); err != nil { 525 c.Fatalf("Error creating .docker directory: %s", err) 526 } 527 if err := libtrust.SaveKey(filepath.Join(os.Getenv("HOME"), ".docker", "key.json"), k1); err != nil { 528 c.Fatalf("Error saving private key: %s", err) 529 } 530 531 s.d.Start(c) 532 s.d.Stop(c) 533 534 k2, err := libtrust.LoadKeyFile("/etc/docker/key.json") 535 if err != nil { 536 c.Fatalf("Error opening key file") 537 } 538 if k1.KeyID() != k2.KeyID() { 539 c.Fatalf("Key not migrated") 540 } 541 } 542 543 // GH#11320 - verify that the daemon exits on failure properly 544 // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means 545 // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required 546 func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) { 547 //attempt to start daemon with incorrect flags (we know -b and --bip conflict) 548 if err := s.d.StartWithError("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { 549 //verify we got the right error 550 if !strings.Contains(err.Error(), "Daemon exited") { 551 c.Fatalf("Expected daemon not to start, got %v", err) 552 } 553 // look in the log and make sure we got the message that daemon is shutting down 554 icmd.RunCommand("grep", "Error starting daemon", s.d.LogFileName()).Assert(c, icmd.Success) 555 } else { 556 //if we didn't get an error and the daemon is running, this is a failure 557 c.Fatal("Conflicting options should cause the daemon to error out with a failure") 558 } 559 } 560 561 func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) { 562 d := s.d 563 err := d.StartWithError("--bridge", "nosuchbridge") 564 c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail")) 565 defer d.Restart(c) 566 567 bridgeName := "external-bridge" 568 bridgeIP := "192.169.1.1/24" 569 _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) 570 571 createInterface(c, "bridge", bridgeName, bridgeIP) 572 defer deleteInterface(c, bridgeName) 573 574 d.StartWithBusybox(c, "--bridge", bridgeName) 575 576 ipTablesSearchString := bridgeIPNet.String() 577 icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ 578 Out: ipTablesSearchString, 579 }) 580 581 _, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top") 582 c.Assert(err, check.IsNil) 583 584 containerIP, err := d.FindContainerIP("ExtContainer") 585 c.Assert(err, checker.IsNil) 586 ip := net.ParseIP(containerIP) 587 c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, 588 check.Commentf("Container IP-Address must be in the same subnet range : %s", 589 containerIP)) 590 } 591 592 func (s *DockerDaemonSuite) TestDaemonBridgeNone(c *check.C) { 593 // start with bridge none 594 d := s.d 595 d.StartWithBusybox(c, "--bridge", "none") 596 defer d.Restart(c) 597 598 // verify docker0 iface is not there 599 icmd.RunCommand("ifconfig", "docker0").Assert(c, icmd.Expected{ 600 ExitCode: 1, 601 Error: "exit status 1", 602 Err: "Device not found", 603 }) 604 605 // verify default "bridge" network is not there 606 out, err := d.Cmd("network", "inspect", "bridge") 607 c.Assert(err, check.NotNil, check.Commentf("\"bridge\" network should not be present if daemon started with --bridge=none")) 608 c.Assert(strings.Contains(out, "No such network"), check.Equals, true) 609 } 610 611 func createInterface(c *check.C, ifType string, ifName string, ipNet string) { 612 icmd.RunCommand("ip", "link", "add", "name", ifName, "type", ifType).Assert(c, icmd.Success) 613 icmd.RunCommand("ifconfig", ifName, ipNet, "up").Assert(c, icmd.Success) 614 } 615 616 func deleteInterface(c *check.C, ifName string) { 617 icmd.RunCommand("ip", "link", "delete", ifName).Assert(c, icmd.Success) 618 icmd.RunCommand("iptables", "-t", "nat", "--flush").Assert(c, icmd.Success) 619 icmd.RunCommand("iptables", "--flush").Assert(c, icmd.Success) 620 } 621 622 func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) { 623 // TestDaemonBridgeIP Steps 624 // 1. Delete the existing docker0 Bridge 625 // 2. Set --bip daemon configuration and start the new Docker Daemon 626 // 3. Check if the bip config has taken effect using ifconfig and iptables commands 627 // 4. Launch a Container and make sure the IP-Address is in the expected subnet 628 // 5. Delete the docker0 Bridge 629 // 6. Restart the Docker Daemon (via deferred action) 630 // This Restart takes care of bringing docker0 interface back to auto-assigned IP 631 632 defaultNetworkBridge := "docker0" 633 deleteInterface(c, defaultNetworkBridge) 634 635 d := s.d 636 637 bridgeIP := "192.169.1.1/24" 638 ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) 639 640 d.StartWithBusybox(c, "--bip", bridgeIP) 641 defer d.Restart(c) 642 643 ifconfigSearchString := ip.String() 644 icmd.RunCommand("ifconfig", defaultNetworkBridge).Assert(c, icmd.Expected{ 645 Out: ifconfigSearchString, 646 }) 647 648 ipTablesSearchString := bridgeIPNet.String() 649 icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ 650 Out: ipTablesSearchString, 651 }) 652 653 _, err := d.Cmd("run", "-d", "--name", "test", "busybox", "top") 654 c.Assert(err, check.IsNil) 655 656 containerIP, err := d.FindContainerIP("test") 657 c.Assert(err, checker.IsNil) 658 ip = net.ParseIP(containerIP) 659 c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, 660 check.Commentf("Container IP-Address must be in the same subnet range : %s", 661 containerIP)) 662 deleteInterface(c, defaultNetworkBridge) 663 } 664 665 func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *check.C) { 666 s.d.Start(c) 667 defer s.d.Restart(c) 668 s.d.Stop(c) 669 670 // now we will change the docker0's IP and then try starting the daemon 671 bridgeIP := "192.169.100.1/24" 672 _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) 673 674 icmd.RunCommand("ifconfig", "docker0", bridgeIP).Assert(c, icmd.Success) 675 676 s.d.Start(c, "--bip", bridgeIP) 677 678 //check if the iptables contains new bridgeIP MASQUERADE rule 679 ipTablesSearchString := bridgeIPNet.String() 680 icmd.RunCommand("iptables", "-t", "nat", "-nvL").Assert(c, icmd.Expected{ 681 Out: ipTablesSearchString, 682 }) 683 } 684 685 func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) { 686 d := s.d 687 688 bridgeName := "external-bridge" 689 bridgeIP := "192.169.1.1/24" 690 691 createInterface(c, "bridge", bridgeName, bridgeIP) 692 defer deleteInterface(c, bridgeName) 693 694 args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"} 695 d.StartWithBusybox(c, args...) 696 defer d.Restart(c) 697 698 for i := 0; i < 4; i++ { 699 cName := "Container" + strconv.Itoa(i) 700 out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") 701 if err != nil { 702 c.Assert(strings.Contains(out, "no available IPv4 addresses"), check.Equals, true, 703 check.Commentf("Could not run a Container : %s %s", err.Error(), out)) 704 } 705 } 706 } 707 708 func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *check.C) { 709 d := s.d 710 711 bridgeName := "external-bridge" 712 bridgeIP := "10.2.2.1/16" 713 714 createInterface(c, "bridge", bridgeName, bridgeIP) 715 defer deleteInterface(c, bridgeName) 716 717 d.StartWithBusybox(c, "--bip", bridgeIP, "--fixed-cidr", "10.2.2.0/24") 718 defer s.d.Restart(c) 719 720 out, err := d.Cmd("run", "-d", "--name", "bb", "busybox", "top") 721 c.Assert(err, checker.IsNil, check.Commentf(out)) 722 defer d.Cmd("stop", "bb") 723 724 out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") 725 c.Assert(out, checker.Equals, "10.2.2.0\n") 726 727 out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") 728 c.Assert(err, checker.IsNil, check.Commentf(out)) 729 c.Assert(out, checker.Equals, "10.2.2.2\n") 730 } 731 732 func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *check.C) { 733 d := s.d 734 735 bridgeName := "external-bridge" 736 bridgeIP := "172.27.42.1/16" 737 738 createInterface(c, "bridge", bridgeName, bridgeIP) 739 defer deleteInterface(c, bridgeName) 740 741 d.StartWithBusybox(c, "--bridge", bridgeName, "--fixed-cidr", bridgeIP) 742 defer s.d.Restart(c) 743 744 out, err := d.Cmd("run", "-d", "busybox", "top") 745 c.Assert(err, check.IsNil, check.Commentf(out)) 746 cid1 := strings.TrimSpace(out) 747 defer d.Cmd("stop", cid1) 748 } 749 750 func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) { 751 defaultNetworkBridge := "docker0" 752 deleteInterface(c, defaultNetworkBridge) 753 754 d := s.d 755 756 bridgeIP := "192.169.1.1" 757 bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP) 758 759 d.StartWithBusybox(c, "--bip", bridgeIPNet) 760 defer d.Restart(c) 761 762 expectedMessage := fmt.Sprintf("default via %s dev", bridgeIP) 763 out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") 764 c.Assert(err, checker.IsNil) 765 c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, 766 check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'", 767 bridgeIP, strings.TrimSpace(out))) 768 deleteInterface(c, defaultNetworkBridge) 769 } 770 771 func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) { 772 defaultNetworkBridge := "docker0" 773 deleteInterface(c, defaultNetworkBridge) 774 775 d := s.d 776 777 bridgeIP := "192.169.1.1" 778 bridgeIPNet := fmt.Sprintf("%s/24", bridgeIP) 779 gatewayIP := "192.169.1.254" 780 781 d.StartWithBusybox(c, "--bip", bridgeIPNet, "--default-gateway", gatewayIP) 782 defer d.Restart(c) 783 784 expectedMessage := fmt.Sprintf("default via %s dev", gatewayIP) 785 out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") 786 c.Assert(err, checker.IsNil) 787 c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, 788 check.Commentf("Explicit default gateway should be %s, but default route was '%s'", 789 gatewayIP, strings.TrimSpace(out))) 790 deleteInterface(c, defaultNetworkBridge) 791 } 792 793 func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4ExplicitOutsideContainerSubnet(c *check.C) { 794 defaultNetworkBridge := "docker0" 795 deleteInterface(c, defaultNetworkBridge) 796 797 // Program a custom default gateway outside of the container subnet, daemon should accept it and start 798 s.d.StartWithBusybox(c, "--bip", "172.16.0.10/16", "--fixed-cidr", "172.16.1.0/24", "--default-gateway", "172.16.0.254") 799 800 deleteInterface(c, defaultNetworkBridge) 801 s.d.Restart(c) 802 } 803 804 func (s *DockerDaemonSuite) TestDaemonDefaultNetworkInvalidClusterConfig(c *check.C) { 805 testRequires(c, DaemonIsLinux, SameHostDaemon) 806 807 // Start daemon without docker0 bridge 808 defaultNetworkBridge := "docker0" 809 deleteInterface(c, defaultNetworkBridge) 810 811 discoveryBackend := "consul://consuladdr:consulport/some/path" 812 s.d.Start(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend)) 813 814 // Start daemon with docker0 bridge 815 result := icmd.RunCommand("ifconfig", defaultNetworkBridge) 816 c.Assert(result, icmd.Matches, icmd.Success) 817 818 s.d.Restart(c, fmt.Sprintf("--cluster-store=%s", discoveryBackend)) 819 } 820 821 func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) { 822 d := s.d 823 824 ipStr := "192.170.1.1/24" 825 ip, _, _ := net.ParseCIDR(ipStr) 826 args := []string{"--ip", ip.String()} 827 d.StartWithBusybox(c, args...) 828 defer d.Restart(c) 829 830 out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") 831 c.Assert(err, check.NotNil, 832 check.Commentf("Running a container must fail with an invalid --ip option")) 833 c.Assert(strings.Contains(out, "Error starting userland proxy"), check.Equals, true) 834 835 ifName := "dummy" 836 createInterface(c, "dummy", ifName, ipStr) 837 defer deleteInterface(c, ifName) 838 839 _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") 840 c.Assert(err, check.IsNil) 841 842 result := icmd.RunCommand("iptables", "-t", "nat", "-nvL") 843 result.Assert(c, icmd.Success) 844 regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String()) 845 matched, _ := regexp.MatchString(regex, result.Combined()) 846 c.Assert(matched, check.Equals, true, 847 check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) 848 } 849 850 func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) { 851 testRequires(c, bridgeNfIptables) 852 d := s.d 853 854 bridgeName := "external-bridge" 855 bridgeIP := "192.169.1.1/24" 856 857 createInterface(c, "bridge", bridgeName, bridgeIP) 858 defer deleteInterface(c, bridgeName) 859 860 d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") 861 defer d.Restart(c) 862 863 result := icmd.RunCommand("iptables", "-nvL", "FORWARD") 864 result.Assert(c, icmd.Success) 865 regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) 866 matched, _ := regexp.MatchString(regex, result.Combined()) 867 c.Assert(matched, check.Equals, true, 868 check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) 869 870 // Pinging another container must fail with --icc=false 871 pingContainers(c, d, true) 872 873 ipStr := "192.171.1.1/24" 874 ip, _, _ := net.ParseCIDR(ipStr) 875 ifName := "icc-dummy" 876 877 createInterface(c, "dummy", ifName, ipStr) 878 879 // But, Pinging external or a Host interface must succeed 880 pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String()) 881 runArgs := []string{"run", "--rm", "busybox", "sh", "-c", pingCmd} 882 _, err := d.Cmd(runArgs...) 883 c.Assert(err, check.IsNil) 884 } 885 886 func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) { 887 d := s.d 888 889 bridgeName := "external-bridge" 890 bridgeIP := "192.169.1.1/24" 891 892 createInterface(c, "bridge", bridgeName, bridgeIP) 893 defer deleteInterface(c, bridgeName) 894 895 d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") 896 defer d.Restart(c) 897 898 result := icmd.RunCommand("iptables", "-nvL", "FORWARD") 899 result.Assert(c, icmd.Success) 900 regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) 901 matched, _ := regexp.MatchString(regex, result.Combined()) 902 c.Assert(matched, check.Equals, true, 903 check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) 904 905 out, err := d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567") 906 c.Assert(err, check.IsNil, check.Commentf(out)) 907 908 out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567") 909 c.Assert(err, check.IsNil, check.Commentf(out)) 910 } 911 912 func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) { 913 bridgeName := "external-bridge" 914 bridgeIP := "192.169.1.1/24" 915 916 createInterface(c, "bridge", bridgeName, bridgeIP) 917 defer deleteInterface(c, bridgeName) 918 919 s.d.StartWithBusybox(c, "--bridge", bridgeName, "--icc=false") 920 defer s.d.Restart(c) 921 922 _, err := s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top") 923 c.Assert(err, check.IsNil) 924 _, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top") 925 c.Assert(err, check.IsNil) 926 927 childIP, err := s.d.FindContainerIP("child") 928 c.Assert(err, checker.IsNil) 929 parentIP, err := s.d.FindContainerIP("parent") 930 c.Assert(err, checker.IsNil) 931 932 sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"} 933 destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"} 934 if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) { 935 c.Fatal("Iptables rules not found") 936 } 937 938 s.d.Cmd("rm", "--link", "parent/http") 939 if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) { 940 c.Fatal("Iptables rules should be removed when unlink") 941 } 942 943 s.d.Cmd("kill", "child") 944 s.d.Cmd("kill", "parent") 945 } 946 947 func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) { 948 testRequires(c, DaemonIsLinux) 949 950 s.d.StartWithBusybox(c, "--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024") 951 952 out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)") 953 if err != nil { 954 c.Fatal(out, err) 955 } 956 957 outArr := strings.Split(out, "\n") 958 if len(outArr) < 2 { 959 c.Fatalf("got unexpected output: %s", out) 960 } 961 nofile := strings.TrimSpace(outArr[0]) 962 nproc := strings.TrimSpace(outArr[1]) 963 964 if nofile != "42" { 965 c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile) 966 } 967 if nproc != "2048" { 968 c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) 969 } 970 971 // Now restart daemon with a new default 972 s.d.Restart(c, "--default-ulimit", "nofile=43") 973 974 out, err = s.d.Cmd("start", "-a", "test") 975 if err != nil { 976 c.Fatal(err) 977 } 978 979 outArr = strings.Split(out, "\n") 980 if len(outArr) < 2 { 981 c.Fatalf("got unexpected output: %s", out) 982 } 983 nofile = strings.TrimSpace(outArr[0]) 984 nproc = strings.TrimSpace(outArr[1]) 985 986 if nofile != "43" { 987 c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile) 988 } 989 if nproc != "2048" { 990 c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) 991 } 992 } 993 994 // #11315 995 func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) { 996 s.d.StartWithBusybox(c) 997 998 if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil { 999 c.Fatal(err, out) 1000 } 1001 1002 if out, err := s.d.Cmd("rename", "test", "test2"); err != nil { 1003 c.Fatal(err, out) 1004 } 1005 1006 s.d.Restart(c) 1007 1008 if out, err := s.d.Cmd("start", "test2"); err != nil { 1009 c.Fatal(err, out) 1010 } 1011 } 1012 1013 func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) { 1014 s.d.StartWithBusybox(c) 1015 1016 out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") 1017 c.Assert(err, check.IsNil, check.Commentf(out)) 1018 id, err := s.d.GetIDByName("test") 1019 c.Assert(err, check.IsNil) 1020 1021 logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") 1022 1023 if _, err := os.Stat(logPath); err != nil { 1024 c.Fatal(err) 1025 } 1026 f, err := os.Open(logPath) 1027 if err != nil { 1028 c.Fatal(err) 1029 } 1030 defer f.Close() 1031 1032 var res struct { 1033 Log string `json:"log"` 1034 Stream string `json:"stream"` 1035 Time time.Time `json:"time"` 1036 } 1037 if err := json.NewDecoder(f).Decode(&res); err != nil { 1038 c.Fatal(err) 1039 } 1040 if res.Log != "testline\n" { 1041 c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") 1042 } 1043 if res.Stream != "stdout" { 1044 c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") 1045 } 1046 if !time.Now().After(res.Time) { 1047 c.Fatalf("Log time %v in future", res.Time) 1048 } 1049 } 1050 1051 func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) { 1052 s.d.StartWithBusybox(c) 1053 1054 out, err := s.d.Cmd("run", "--name=test", "--log-driver=none", "busybox", "echo", "testline") 1055 if err != nil { 1056 c.Fatal(out, err) 1057 } 1058 id, err := s.d.GetIDByName("test") 1059 c.Assert(err, check.IsNil) 1060 1061 logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") 1062 1063 if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { 1064 c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) 1065 } 1066 } 1067 1068 func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) { 1069 s.d.StartWithBusybox(c, "--log-driver=none") 1070 1071 out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") 1072 if err != nil { 1073 c.Fatal(out, err) 1074 } 1075 id, err := s.d.GetIDByName("test") 1076 c.Assert(err, check.IsNil) 1077 1078 logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") 1079 1080 if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { 1081 c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) 1082 } 1083 } 1084 1085 func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { 1086 s.d.StartWithBusybox(c, "--log-driver=none") 1087 1088 out, err := s.d.Cmd("run", "--name=test", "--log-driver=json-file", "busybox", "echo", "testline") 1089 if err != nil { 1090 c.Fatal(out, err) 1091 } 1092 id, err := s.d.GetIDByName("test") 1093 c.Assert(err, check.IsNil) 1094 1095 logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") 1096 1097 if _, err := os.Stat(logPath); err != nil { 1098 c.Fatal(err) 1099 } 1100 f, err := os.Open(logPath) 1101 if err != nil { 1102 c.Fatal(err) 1103 } 1104 defer f.Close() 1105 1106 var res struct { 1107 Log string `json:"log"` 1108 Stream string `json:"stream"` 1109 Time time.Time `json:"time"` 1110 } 1111 if err := json.NewDecoder(f).Decode(&res); err != nil { 1112 c.Fatal(err) 1113 } 1114 if res.Log != "testline\n" { 1115 c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") 1116 } 1117 if res.Stream != "stdout" { 1118 c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") 1119 } 1120 if !time.Now().After(res.Time) { 1121 c.Fatalf("Log time %v in future", res.Time) 1122 } 1123 } 1124 1125 func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { 1126 s.d.StartWithBusybox(c, "--log-driver=none") 1127 1128 out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") 1129 c.Assert(err, checker.IsNil, check.Commentf(out)) 1130 1131 out, err = s.d.Cmd("logs", "test") 1132 c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver")) 1133 expected := `configured logging driver does not support reading` 1134 c.Assert(out, checker.Contains, expected) 1135 } 1136 1137 func (s *DockerDaemonSuite) TestDaemonLoggingDriverShouldBeIgnoredForBuild(c *check.C) { 1138 s.d.StartWithBusybox(c, "--log-driver=splunk") 1139 1140 out, err := s.d.Cmd("build") 1141 out, code, err := s.d.BuildImageWithOut("busyboxs", ` 1142 FROM busybox 1143 RUN echo foo`, false) 1144 comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err) 1145 c.Assert(err, check.IsNil, comment) 1146 c.Assert(code, check.Equals, 0, comment) 1147 c.Assert(out, checker.Contains, "foo", comment) 1148 } 1149 1150 func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) { 1151 dir, err := ioutil.TempDir("", "socket-cleanup-test") 1152 if err != nil { 1153 c.Fatal(err) 1154 } 1155 defer os.RemoveAll(dir) 1156 1157 sockPath := filepath.Join(dir, "docker.sock") 1158 s.d.Start(c, "--host", "unix://"+sockPath) 1159 1160 if _, err := os.Stat(sockPath); err != nil { 1161 c.Fatal("socket does not exist") 1162 } 1163 1164 s.d.Stop(c) 1165 1166 if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) { 1167 c.Fatal("unix socket is not cleaned up") 1168 } 1169 } 1170 1171 func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) { 1172 type Config struct { 1173 Crv string `json:"crv"` 1174 D string `json:"d"` 1175 Kid string `json:"kid"` 1176 Kty string `json:"kty"` 1177 X string `json:"x"` 1178 Y string `json:"y"` 1179 } 1180 1181 os.Remove("/etc/docker/key.json") 1182 s.d.Start(c) 1183 s.d.Stop(c) 1184 1185 config := &Config{} 1186 bytes, err := ioutil.ReadFile("/etc/docker/key.json") 1187 if err != nil { 1188 c.Fatalf("Error reading key.json file: %s", err) 1189 } 1190 1191 // byte[] to Data-Struct 1192 if err := json.Unmarshal(bytes, &config); err != nil { 1193 c.Fatalf("Error Unmarshal: %s", err) 1194 } 1195 1196 //replace config.Kid with the fake value 1197 config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4" 1198 1199 // NEW Data-Struct to byte[] 1200 newBytes, err := json.Marshal(&config) 1201 if err != nil { 1202 c.Fatalf("Error Marshal: %s", err) 1203 } 1204 1205 // write back 1206 if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil { 1207 c.Fatalf("Error ioutil.WriteFile: %s", err) 1208 } 1209 1210 defer os.Remove("/etc/docker/key.json") 1211 1212 if err := s.d.StartWithError(); err == nil { 1213 c.Fatalf("It should not be successful to start daemon with wrong key: %v", err) 1214 } 1215 1216 content, err := s.d.ReadLogFile() 1217 c.Assert(err, checker.IsNil) 1218 1219 if !strings.Contains(string(content), "Public Key ID does not match") { 1220 c.Fatalf("Missing KeyID message from daemon logs: %s", string(content)) 1221 } 1222 } 1223 1224 func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) { 1225 s.d.StartWithBusybox(c) 1226 1227 out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat") 1228 if err != nil { 1229 c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out) 1230 } 1231 containerID := strings.TrimSpace(out) 1232 1233 if out, err := s.d.Cmd("kill", containerID); err != nil { 1234 c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out) 1235 } 1236 1237 s.d.Restart(c) 1238 1239 errchan := make(chan error) 1240 go func() { 1241 if out, err := s.d.Cmd("wait", containerID); err != nil { 1242 errchan <- fmt.Errorf("%v:\n%s", err, out) 1243 } 1244 close(errchan) 1245 }() 1246 1247 select { 1248 case <-time.After(5 * time.Second): 1249 c.Fatal("Waiting on a stopped (killed) container timed out") 1250 case err := <-errchan: 1251 if err != nil { 1252 c.Fatal(err) 1253 } 1254 } 1255 } 1256 1257 // TestHTTPSInfo connects via two-way authenticated HTTPS to the info endpoint 1258 func (s *DockerDaemonSuite) TestHTTPSInfo(c *check.C) { 1259 const ( 1260 testDaemonHTTPSAddr = "tcp://localhost:4271" 1261 ) 1262 1263 s.d.Start(c, 1264 "--tlsverify", 1265 "--tlscacert", "fixtures/https/ca.pem", 1266 "--tlscert", "fixtures/https/server-cert.pem", 1267 "--tlskey", "fixtures/https/server-key.pem", 1268 "-H", testDaemonHTTPSAddr) 1269 1270 args := []string{ 1271 "--host", testDaemonHTTPSAddr, 1272 "--tlsverify", 1273 "--tlscacert", "fixtures/https/ca.pem", 1274 "--tlscert", "fixtures/https/client-cert.pem", 1275 "--tlskey", "fixtures/https/client-key.pem", 1276 "info", 1277 } 1278 out, err := s.d.Cmd(args...) 1279 if err != nil { 1280 c.Fatalf("Error Occurred: %s and output: %s", err, out) 1281 } 1282 } 1283 1284 // TestHTTPSRun connects via two-way authenticated HTTPS to the create, attach, start, and wait endpoints. 1285 // https://github.com/docker/docker/issues/19280 1286 func (s *DockerDaemonSuite) TestHTTPSRun(c *check.C) { 1287 const ( 1288 testDaemonHTTPSAddr = "tcp://localhost:4271" 1289 ) 1290 1291 s.d.StartWithBusybox(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", 1292 "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHTTPSAddr) 1293 1294 args := []string{ 1295 "--host", testDaemonHTTPSAddr, 1296 "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", 1297 "--tlscert", "fixtures/https/client-cert.pem", 1298 "--tlskey", "fixtures/https/client-key.pem", 1299 "run", "busybox", "echo", "TLS response", 1300 } 1301 out, err := s.d.Cmd(args...) 1302 if err != nil { 1303 c.Fatalf("Error Occurred: %s and output: %s", err, out) 1304 } 1305 1306 if !strings.Contains(out, "TLS response") { 1307 c.Fatalf("expected output to include `TLS response`, got %v", out) 1308 } 1309 } 1310 1311 // TestTLSVerify verifies that --tlsverify=false turns on tls 1312 func (s *DockerDaemonSuite) TestTLSVerify(c *check.C) { 1313 out, err := exec.Command(dockerdBinary, "--tlsverify=false").CombinedOutput() 1314 if err == nil || !strings.Contains(string(out), "Could not load X509 key pair") { 1315 c.Fatalf("Daemon should not have started due to missing certs: %v\n%s", err, string(out)) 1316 } 1317 } 1318 1319 // TestHTTPSInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint 1320 // by using a rogue client certificate and checks that it fails with the expected error. 1321 func (s *DockerDaemonSuite) TestHTTPSInfoRogueCert(c *check.C) { 1322 const ( 1323 errBadCertificate = "bad certificate" 1324 testDaemonHTTPSAddr = "tcp://localhost:4271" 1325 ) 1326 1327 s.d.Start(c, 1328 "--tlsverify", 1329 "--tlscacert", "fixtures/https/ca.pem", 1330 "--tlscert", "fixtures/https/server-cert.pem", 1331 "--tlskey", "fixtures/https/server-key.pem", 1332 "-H", testDaemonHTTPSAddr) 1333 1334 args := []string{ 1335 "--host", testDaemonHTTPSAddr, 1336 "--tlsverify", 1337 "--tlscacert", "fixtures/https/ca.pem", 1338 "--tlscert", "fixtures/https/client-rogue-cert.pem", 1339 "--tlskey", "fixtures/https/client-rogue-key.pem", 1340 "info", 1341 } 1342 out, err := s.d.Cmd(args...) 1343 if err == nil || !strings.Contains(out, errBadCertificate) { 1344 c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out) 1345 } 1346 } 1347 1348 // TestHTTPSInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint 1349 // which provides a rogue server certificate and checks that it fails with the expected error 1350 func (s *DockerDaemonSuite) TestHTTPSInfoRogueServerCert(c *check.C) { 1351 const ( 1352 errCaUnknown = "x509: certificate signed by unknown authority" 1353 testDaemonRogueHTTPSAddr = "tcp://localhost:4272" 1354 ) 1355 s.d.Start(c, 1356 "--tlsverify", 1357 "--tlscacert", "fixtures/https/ca.pem", 1358 "--tlscert", "fixtures/https/server-rogue-cert.pem", 1359 "--tlskey", "fixtures/https/server-rogue-key.pem", 1360 "-H", testDaemonRogueHTTPSAddr) 1361 1362 args := []string{ 1363 "--host", testDaemonRogueHTTPSAddr, 1364 "--tlsverify", 1365 "--tlscacert", "fixtures/https/ca.pem", 1366 "--tlscert", "fixtures/https/client-rogue-cert.pem", 1367 "--tlskey", "fixtures/https/client-rogue-key.pem", 1368 "info", 1369 } 1370 out, err := s.d.Cmd(args...) 1371 if err == nil || !strings.Contains(out, errCaUnknown) { 1372 c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out) 1373 } 1374 } 1375 1376 func pingContainers(c *check.C, d *daemon.Daemon, expectFailure bool) { 1377 var dargs []string 1378 if d != nil { 1379 dargs = []string{"--host", d.Sock()} 1380 } 1381 1382 args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top") 1383 dockerCmd(c, args...) 1384 1385 args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c") 1386 pingCmd := "ping -c 1 %s -W 1" 1387 args = append(args, fmt.Sprintf(pingCmd, "alias1")) 1388 _, _, err := dockerCmdWithError(args...) 1389 1390 if expectFailure { 1391 c.Assert(err, check.NotNil) 1392 } else { 1393 c.Assert(err, check.IsNil) 1394 } 1395 1396 args = append(dargs, "rm", "-f", "container1") 1397 dockerCmd(c, args...) 1398 } 1399 1400 func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) { 1401 s.d.StartWithBusybox(c) 1402 1403 socket := filepath.Join(s.d.Folder, "docker.sock") 1404 1405 out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox") 1406 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1407 s.d.Restart(c) 1408 } 1409 1410 // os.Kill should kill daemon ungracefully, leaving behind container mounts. 1411 // A subsequent daemon restart shoud clean up said mounts. 1412 func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *check.C) { 1413 d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ 1414 Experimental: testEnv.ExperimentalDaemon(), 1415 }) 1416 d.StartWithBusybox(c) 1417 1418 out, err := d.Cmd("run", "-d", "busybox", "top") 1419 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1420 id := strings.TrimSpace(out) 1421 c.Assert(d.Signal(os.Kill), check.IsNil) 1422 mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") 1423 c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) 1424 1425 // container mounts should exist even after daemon has crashed. 1426 comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) 1427 c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment) 1428 1429 // kill the container 1430 icmd.RunCommand(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", id).Assert(c, icmd.Success) 1431 1432 // restart daemon. 1433 d.Restart(c) 1434 1435 // Now, container mounts should be gone. 1436 mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") 1437 c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) 1438 comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) 1439 c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) 1440 1441 d.Stop(c) 1442 } 1443 1444 // os.Interrupt should perform a graceful daemon shutdown and hence cleanup mounts. 1445 func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) { 1446 d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ 1447 Experimental: testEnv.ExperimentalDaemon(), 1448 }) 1449 d.StartWithBusybox(c) 1450 1451 out, err := d.Cmd("run", "-d", "busybox", "top") 1452 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1453 id := strings.TrimSpace(out) 1454 1455 // Send SIGINT and daemon should clean up 1456 c.Assert(d.Signal(os.Interrupt), check.IsNil) 1457 // Wait for the daemon to stop. 1458 c.Assert(<-d.Wait, checker.IsNil) 1459 1460 mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") 1461 c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) 1462 1463 comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) 1464 c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) 1465 } 1466 1467 func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) { 1468 testRequires(c, DaemonIsLinux, NotUserNamespace) 1469 s.d.StartWithBusybox(c, "-b", "none") 1470 1471 out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l") 1472 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1473 c.Assert(strings.Contains(out, "eth0"), check.Equals, false, 1474 check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out)) 1475 1476 out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l") 1477 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1478 c.Assert(strings.Contains(out, "eth0"), check.Equals, false, 1479 check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out)) 1480 // the extra grep and awk clean up the output of `ip` to only list the number and name of 1481 // interfaces, allowing for different versions of ip (e.g. inside and outside the container) to 1482 // be used while still verifying that the interface list is the exact same 1483 cmd := exec.Command("sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '") 1484 stdout := bytes.NewBuffer(nil) 1485 cmd.Stdout = stdout 1486 if err := cmd.Run(); err != nil { 1487 c.Fatal("Failed to get host network interface") 1488 } 1489 out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "sh", "-c", "ip l | grep -E '^[0-9]+:' | awk -F: ' { print $1\":\"$2 } '") 1490 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1491 c.Assert(out, check.Equals, fmt.Sprintf("%s", stdout), 1492 check.Commentf("The network interfaces in container should be the same with host when --net=host when bridge network is disabled: %s", out)) 1493 } 1494 1495 func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) { 1496 s.d.StartWithBusybox(t) 1497 if out, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top"); err != nil { 1498 t.Fatal(out, err) 1499 } 1500 1501 s.d.Restart(t) 1502 // Container 'test' should be removed without error 1503 if out, err := s.d.Cmd("rm", "test"); err != nil { 1504 t.Fatal(out, err) 1505 } 1506 } 1507 1508 func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) { 1509 s.d.StartWithBusybox(c) 1510 out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top") 1511 if err != nil { 1512 c.Fatal(out, err) 1513 } 1514 1515 // Get sandbox key via inspect 1516 out, err = s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.SandboxKey}}'", "netns") 1517 if err != nil { 1518 c.Fatalf("Error inspecting container: %s, %v", out, err) 1519 } 1520 fileName := strings.Trim(out, " \r\n'") 1521 1522 if out, err := s.d.Cmd("stop", "netns"); err != nil { 1523 c.Fatal(out, err) 1524 } 1525 1526 // Test if the file still exists 1527 icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{ 1528 Out: fileName, 1529 }) 1530 1531 // Remove the container and restart the daemon 1532 if out, err := s.d.Cmd("rm", "netns"); err != nil { 1533 c.Fatal(out, err) 1534 } 1535 1536 s.d.Restart(c) 1537 1538 // Test again and see now the netns file does not exist 1539 icmd.RunCommand("stat", "-c", "%n", fileName).Assert(c, icmd.Expected{ 1540 Err: "No such file or directory", 1541 ExitCode: 1, 1542 }) 1543 } 1544 1545 // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored 1546 func (s *DockerDaemonSuite) TestDaemonTLSVerifyIssue13964(c *check.C) { 1547 host := "tcp://localhost:4271" 1548 s.d.Start(c, "-H", host) 1549 icmd.RunCmd(icmd.Cmd{ 1550 Command: []string{dockerBinary, "-H", host, "info"}, 1551 Env: []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"}, 1552 }).Assert(c, icmd.Expected{ 1553 ExitCode: 1, 1554 Err: "error during connect", 1555 }) 1556 } 1557 1558 func setupV6(c *check.C) { 1559 // Hack to get the right IPv6 address on docker0, which has already been created 1560 result := icmd.RunCommand("ip", "addr", "add", "fe80::1/64", "dev", "docker0") 1561 result.Assert(c, icmd.Success) 1562 } 1563 1564 func teardownV6(c *check.C) { 1565 result := icmd.RunCommand("ip", "addr", "del", "fe80::1/64", "dev", "docker0") 1566 result.Assert(c, icmd.Success) 1567 } 1568 1569 func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlways(c *check.C) { 1570 s.d.StartWithBusybox(c) 1571 1572 out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") 1573 c.Assert(err, check.IsNil) 1574 id := strings.TrimSpace(out) 1575 1576 _, err = s.d.Cmd("stop", id) 1577 c.Assert(err, check.IsNil) 1578 _, err = s.d.Cmd("wait", id) 1579 c.Assert(err, check.IsNil) 1580 1581 out, err = s.d.Cmd("ps", "-q") 1582 c.Assert(err, check.IsNil) 1583 c.Assert(out, check.Equals, "") 1584 1585 s.d.Restart(c) 1586 1587 out, err = s.d.Cmd("ps", "-q") 1588 c.Assert(err, check.IsNil) 1589 c.Assert(strings.TrimSpace(out), check.Equals, id[:12]) 1590 } 1591 1592 func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) { 1593 s.d.StartWithBusybox(c, "--log-opt=max-size=1k") 1594 name := "logtest" 1595 out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top") 1596 c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err)) 1597 1598 out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name) 1599 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1600 c.Assert(out, checker.Contains, "max-size:1k") 1601 c.Assert(out, checker.Contains, "max-file:5") 1602 1603 out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name) 1604 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1605 c.Assert(strings.TrimSpace(out), checker.Equals, "json-file") 1606 } 1607 1608 func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) { 1609 s.d.StartWithBusybox(c) 1610 if out, err := s.d.Cmd("run", "-i", "-d", "--name", "test", "busybox", "top"); err != nil { 1611 c.Fatal(err, out) 1612 } 1613 if out, err := s.d.Cmd("pause", "test"); err != nil { 1614 c.Fatal(err, out) 1615 } 1616 s.d.Restart(c) 1617 1618 errchan := make(chan error) 1619 go func() { 1620 out, err := s.d.Cmd("start", "test") 1621 if err != nil { 1622 errchan <- fmt.Errorf("%v:\n%s", err, out) 1623 } 1624 name := strings.TrimSpace(out) 1625 if name != "test" { 1626 errchan <- fmt.Errorf("Paused container start error on docker daemon restart, expected 'test' but got '%s'", name) 1627 } 1628 close(errchan) 1629 }() 1630 1631 select { 1632 case <-time.After(5 * time.Second): 1633 c.Fatal("Waiting on start a container timed out") 1634 case err := <-errchan: 1635 if err != nil { 1636 c.Fatal(err) 1637 } 1638 } 1639 } 1640 1641 func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) { 1642 s.d.StartWithBusybox(c) 1643 1644 out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox") 1645 c.Assert(err, check.IsNil, check.Commentf(out)) 1646 1647 s.d.Restart(c) 1648 1649 out, err = s.d.Cmd("volume", "rm", "test") 1650 c.Assert(err, check.NotNil, check.Commentf("should not be able to remove in use volume after daemon restart")) 1651 c.Assert(out, checker.Contains, "in use") 1652 } 1653 1654 func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) { 1655 s.d.Start(c) 1656 1657 _, err := s.d.Cmd("volume", "create", "test") 1658 c.Assert(err, check.IsNil) 1659 s.d.Restart(c) 1660 1661 _, err = s.d.Cmd("volume", "inspect", "test") 1662 c.Assert(err, check.IsNil) 1663 } 1664 1665 // FIXME(vdemeester) should be a unit test 1666 func (s *DockerDaemonSuite) TestDaemonCorruptedLogDriverAddress(c *check.C) { 1667 d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ 1668 Experimental: testEnv.ExperimentalDaemon(), 1669 }) 1670 c.Assert(d.StartWithError("--log-driver=syslog", "--log-opt", "syslog-address=corrupted:42"), check.NotNil) 1671 expected := "Failed to set log opts: syslog-address should be in form proto://address" 1672 icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) 1673 } 1674 1675 // FIXME(vdemeester) should be a unit test 1676 func (s *DockerDaemonSuite) TestDaemonCorruptedFluentdAddress(c *check.C) { 1677 d := daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{ 1678 Experimental: testEnv.ExperimentalDaemon(), 1679 }) 1680 c.Assert(d.StartWithError("--log-driver=fluentd", "--log-opt", "fluentd-address=corrupted:c"), check.NotNil) 1681 expected := "Failed to set log opts: invalid fluentd-address corrupted:c: " 1682 icmd.RunCommand("grep", expected, d.LogFileName()).Assert(c, icmd.Success) 1683 } 1684 1685 // FIXME(vdemeester) Use a new daemon instance instead of the Suite one 1686 func (s *DockerDaemonSuite) TestDaemonStartWithoutHost(c *check.C) { 1687 s.d.UseDefaultHost = true 1688 defer func() { 1689 s.d.UseDefaultHost = false 1690 }() 1691 s.d.Start(c) 1692 } 1693 1694 // FIXME(vdemeester) Use a new daemon instance instead of the Suite one 1695 func (s *DockerDaemonSuite) TestDaemonStartWithDefalutTLSHost(c *check.C) { 1696 s.d.UseDefaultTLSHost = true 1697 defer func() { 1698 s.d.UseDefaultTLSHost = false 1699 }() 1700 s.d.Start(c, 1701 "--tlsverify", 1702 "--tlscacert", "fixtures/https/ca.pem", 1703 "--tlscert", "fixtures/https/server-cert.pem", 1704 "--tlskey", "fixtures/https/server-key.pem") 1705 1706 // The client with --tlsverify should also use default host localhost:2376 1707 tmpHost := os.Getenv("DOCKER_HOST") 1708 defer func() { 1709 os.Setenv("DOCKER_HOST", tmpHost) 1710 }() 1711 1712 os.Setenv("DOCKER_HOST", "") 1713 1714 out, _ := dockerCmd( 1715 c, 1716 "--tlsverify", 1717 "--tlscacert", "fixtures/https/ca.pem", 1718 "--tlscert", "fixtures/https/client-cert.pem", 1719 "--tlskey", "fixtures/https/client-key.pem", 1720 "version", 1721 ) 1722 if !strings.Contains(out, "Server") { 1723 c.Fatalf("docker version should return information of server side") 1724 } 1725 } 1726 1727 func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) { 1728 defaultNetworkBridge := "docker0" 1729 deleteInterface(c, defaultNetworkBridge) 1730 1731 bridgeIP := "192.169.1.1" 1732 bridgeRange := bridgeIP + "/30" 1733 1734 s.d.StartWithBusybox(c, "--bip", bridgeRange) 1735 defer s.d.Restart(c) 1736 1737 var cont int 1738 for { 1739 contName := fmt.Sprintf("container%d", cont) 1740 _, err := s.d.Cmd("run", "--name", contName, "-d", "busybox", "/bin/sleep", "2") 1741 if err != nil { 1742 // pool exhausted 1743 break 1744 } 1745 ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName) 1746 c.Assert(err, check.IsNil) 1747 1748 c.Assert(ip, check.Not(check.Equals), bridgeIP) 1749 cont++ 1750 } 1751 } 1752 1753 // Test daemon for no space left on device error 1754 func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) { 1755 testRequires(c, SameHostDaemon, DaemonIsLinux, Network) 1756 1757 testDir, err := ioutil.TempDir("", "no-space-left-on-device-test") 1758 c.Assert(err, checker.IsNil) 1759 defer os.RemoveAll(testDir) 1760 c.Assert(mount.MakeRShared(testDir), checker.IsNil) 1761 defer mount.Unmount(testDir) 1762 1763 // create a 2MiB image and mount it as graph root 1764 // Why in a container? Because `mount` sometimes behaves weirdly and often fails outright on this test in debian:jessie (which is what the test suite runs under if run from the Makefile) 1765 dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=2 count=0") 1766 icmd.RunCommand("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img")).Assert(c, icmd.Success) 1767 1768 result := icmd.RunCommand("losetup", "-f", "--show", filepath.Join(testDir, "testfs.img")) 1769 result.Assert(c, icmd.Success) 1770 loopname := strings.TrimSpace(string(result.Combined())) 1771 defer exec.Command("losetup", "-d", loopname).Run() 1772 1773 dockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", fmt.Sprintf("mkdir -p /test/test-mount && mount -t ext4 -no loop,rw %v /test/test-mount", loopname)) 1774 defer mount.Unmount(filepath.Join(testDir, "test-mount")) 1775 1776 s.d.Start(c, "--graph", filepath.Join(testDir, "test-mount")) 1777 defer s.d.Stop(c) 1778 1779 // pull a repository large enough to fill the mount point 1780 pullOut, err := s.d.Cmd("pull", "registry:2") 1781 c.Assert(err, checker.NotNil, check.Commentf(pullOut)) 1782 c.Assert(pullOut, checker.Contains, "no space left on device") 1783 } 1784 1785 // Test daemon restart with container links + auto restart 1786 func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) { 1787 s.d.StartWithBusybox(c) 1788 1789 parent1Args := []string{} 1790 parent2Args := []string{} 1791 wg := sync.WaitGroup{} 1792 maxChildren := 10 1793 chErr := make(chan error, maxChildren) 1794 1795 for i := 0; i < maxChildren; i++ { 1796 wg.Add(1) 1797 name := fmt.Sprintf("test%d", i) 1798 1799 if i < maxChildren/2 { 1800 parent1Args = append(parent1Args, []string{"--link", name}...) 1801 } else { 1802 parent2Args = append(parent2Args, []string{"--link", name}...) 1803 } 1804 1805 go func() { 1806 _, err := s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top") 1807 chErr <- err 1808 wg.Done() 1809 }() 1810 } 1811 1812 wg.Wait() 1813 close(chErr) 1814 for err := range chErr { 1815 c.Assert(err, check.IsNil) 1816 } 1817 1818 parent1Args = append([]string{"run", "-d"}, parent1Args...) 1819 parent1Args = append(parent1Args, []string{"--name=parent1", "--restart=always", "busybox", "top"}...) 1820 parent2Args = append([]string{"run", "-d"}, parent2Args...) 1821 parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...) 1822 1823 _, err := s.d.Cmd(parent1Args...) 1824 c.Assert(err, check.IsNil) 1825 _, err = s.d.Cmd(parent2Args...) 1826 c.Assert(err, check.IsNil) 1827 1828 s.d.Stop(c) 1829 // clear the log file -- we don't need any of it but may for the next part 1830 // can ignore the error here, this is just a cleanup 1831 os.Truncate(s.d.LogFileName(), 0) 1832 s.d.Start(c) 1833 1834 for _, num := range []string{"1", "2"} { 1835 out, err := s.d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num) 1836 c.Assert(err, check.IsNil) 1837 if strings.TrimSpace(out) != "true" { 1838 log, _ := ioutil.ReadFile(s.d.LogFileName()) 1839 c.Fatalf("parent container is not running\n%s", string(log)) 1840 } 1841 } 1842 } 1843 1844 func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) { 1845 testRequires(c, DaemonIsLinux) 1846 1847 cgroupParent := "test" 1848 name := "cgroup-test" 1849 1850 s.d.StartWithBusybox(c, "--cgroup-parent", cgroupParent) 1851 defer s.d.Restart(c) 1852 1853 out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup") 1854 c.Assert(err, checker.IsNil) 1855 cgroupPaths := testutil.ParseCgroupPaths(string(out)) 1856 c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out))) 1857 out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name) 1858 c.Assert(err, checker.IsNil) 1859 id := strings.TrimSpace(string(out)) 1860 expectedCgroup := path.Join(cgroupParent, id) 1861 found := false 1862 for _, path := range cgroupPaths { 1863 if strings.HasSuffix(path, expectedCgroup) { 1864 found = true 1865 break 1866 } 1867 } 1868 c.Assert(found, checker.True, check.Commentf("Cgroup path for container (%s) doesn't found in cgroups file: %s", expectedCgroup, cgroupPaths)) 1869 } 1870 1871 func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) { 1872 testRequires(c, DaemonIsLinux) // Windows does not support links 1873 s.d.StartWithBusybox(c) 1874 1875 out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") 1876 c.Assert(err, check.IsNil, check.Commentf(out)) 1877 1878 out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc") 1879 c.Assert(err, check.IsNil, check.Commentf(out)) 1880 1881 s.d.Restart(c) 1882 1883 // should fail since test is not running yet 1884 out, err = s.d.Cmd("start", "test2") 1885 c.Assert(err, check.NotNil, check.Commentf(out)) 1886 1887 out, err = s.d.Cmd("start", "test") 1888 c.Assert(err, check.IsNil, check.Commentf(out)) 1889 out, err = s.d.Cmd("start", "-a", "test2") 1890 c.Assert(err, check.IsNil, check.Commentf(out)) 1891 c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf(out)) 1892 } 1893 1894 func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) { 1895 testRequires(c, DaemonIsLinux) // Windows does not support links 1896 s.d.StartWithBusybox(c) 1897 1898 out, err := s.d.Cmd("create", "--name=test", "busybox") 1899 c.Assert(err, check.IsNil, check.Commentf(out)) 1900 1901 out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top") 1902 c.Assert(err, check.IsNil, check.Commentf(out)) 1903 test2ID := strings.TrimSpace(out) 1904 1905 out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top") 1906 test3ID := strings.TrimSpace(out) 1907 1908 s.d.Restart(c) 1909 1910 out, err = s.d.Cmd("create", "--name=test", "busybox") 1911 c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name")) 1912 // this one is no longer needed, removing simplifies the remainder of the test 1913 out, err = s.d.Cmd("rm", "-f", "test") 1914 c.Assert(err, check.IsNil, check.Commentf(out)) 1915 1916 out, err = s.d.Cmd("ps", "-a", "--no-trunc") 1917 c.Assert(err, check.IsNil, check.Commentf(out)) 1918 1919 lines := strings.Split(strings.TrimSpace(out), "\n")[1:] 1920 1921 test2validated := false 1922 test3validated := false 1923 for _, line := range lines { 1924 fields := strings.Fields(line) 1925 names := fields[len(fields)-1] 1926 switch fields[0] { 1927 case test2ID: 1928 c.Assert(names, check.Equals, "test2,test3/abc") 1929 test2validated = true 1930 case test3ID: 1931 c.Assert(names, check.Equals, "test3") 1932 test3validated = true 1933 } 1934 } 1935 1936 c.Assert(test2validated, check.Equals, true) 1937 c.Assert(test3validated, check.Equals, true) 1938 } 1939 1940 // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers 1941 func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check.C) { 1942 // TODO(mlaventure): Not sure what would the exit code be on windows 1943 testRequires(t, DaemonIsLinux) 1944 s.d.StartWithBusybox(t) 1945 1946 cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top") 1947 defer s.d.Stop(t) 1948 if err != nil { 1949 t.Fatal(cid, err) 1950 } 1951 cid = strings.TrimSpace(cid) 1952 1953 pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) 1954 t.Assert(err, check.IsNil) 1955 pid = strings.TrimSpace(pid) 1956 1957 // Kill the daemon 1958 if err := s.d.Kill(); err != nil { 1959 t.Fatal(err) 1960 } 1961 1962 // kill the container 1963 icmd.RunCommand(ctrBinary, "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", "containers", "kill", cid).Assert(t, icmd.Success) 1964 1965 // Give time to containerd to process the command if we don't 1966 // the exit event might be received after we do the inspect 1967 result := icmd.RunCommand("kill", "-0", pid) 1968 for result.ExitCode == 0 { 1969 time.Sleep(1 * time.Second) 1970 // FIXME(vdemeester) should we check it doesn't error out ? 1971 result = icmd.RunCommand("kill", "-0", pid) 1972 } 1973 1974 // restart the daemon 1975 s.d.Start(t) 1976 1977 // Check that we've got the correct exit code 1978 out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid) 1979 t.Assert(err, check.IsNil) 1980 1981 out = strings.TrimSpace(out) 1982 if out != "143" { 1983 t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "143", out, cid) 1984 } 1985 1986 } 1987 1988 // os.Kill should kill daemon ungracefully, leaving behind live containers. 1989 // The live containers should be known to the restarted daemon. Stopping 1990 // them now, should remove the mounts. 1991 func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) { 1992 testRequires(c, DaemonIsLinux) 1993 s.d.StartWithBusybox(c, "--live-restore") 1994 1995 out, err := s.d.Cmd("run", "-d", "busybox", "top") 1996 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 1997 id := strings.TrimSpace(out) 1998 1999 c.Assert(s.d.Signal(os.Kill), check.IsNil) 2000 mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") 2001 c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) 2002 2003 // container mounts should exist even after daemon has crashed. 2004 comment := check.Commentf("%s should stay mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut) 2005 c.Assert(strings.Contains(string(mountOut), id), check.Equals, true, comment) 2006 2007 // restart daemon. 2008 s.d.Start(c, "--live-restore") 2009 2010 // container should be running. 2011 out, err = s.d.Cmd("inspect", "--format={{.State.Running}}", id) 2012 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2013 out = strings.TrimSpace(out) 2014 if out != "true" { 2015 c.Fatalf("Container %s expected to stay alive after daemon restart", id) 2016 } 2017 2018 // 'docker stop' should work. 2019 out, err = s.d.Cmd("stop", id) 2020 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2021 2022 // Now, container mounts should be gone. 2023 mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") 2024 c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) 2025 comment = check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, s.d.Root, mountOut) 2026 c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) 2027 } 2028 2029 // TestDaemonRestartWithUnpausedRunningContainer requires live restore of running containers. 2030 func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *check.C) { 2031 // TODO(mlaventure): Not sure what would the exit code be on windows 2032 testRequires(t, DaemonIsLinux) 2033 s.d.StartWithBusybox(t, "--live-restore") 2034 2035 cid, err := s.d.Cmd("run", "-d", "--name", "test", "busybox", "top") 2036 defer s.d.Stop(t) 2037 if err != nil { 2038 t.Fatal(cid, err) 2039 } 2040 cid = strings.TrimSpace(cid) 2041 2042 pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) 2043 t.Assert(err, check.IsNil) 2044 2045 // pause the container 2046 if _, err := s.d.Cmd("pause", cid); err != nil { 2047 t.Fatal(cid, err) 2048 } 2049 2050 // Kill the daemon 2051 if err := s.d.Kill(); err != nil { 2052 t.Fatal(err) 2053 } 2054 2055 // resume the container 2056 result := icmd.RunCommand( 2057 ctrBinary, 2058 "--address", "unix:///var/run/docker/libcontainerd/docker-containerd.sock", 2059 "containers", "resume", cid) 2060 t.Assert(result, icmd.Matches, icmd.Success) 2061 2062 // Give time to containerd to process the command if we don't 2063 // the resume event might be received after we do the inspect 2064 waitAndAssert(t, defaultReconciliationTimeout, func(*check.C) (interface{}, check.CommentInterface) { 2065 result := icmd.RunCommand("kill", "-0", strings.TrimSpace(pid)) 2066 return result.ExitCode, nil 2067 }, checker.Equals, 0) 2068 2069 // restart the daemon 2070 s.d.Start(t, "--live-restore") 2071 2072 // Check that we've got the correct status 2073 out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid) 2074 t.Assert(err, check.IsNil) 2075 2076 out = strings.TrimSpace(out) 2077 if out != "running" { 2078 t.Fatalf("Expected exit code '%s' got '%s' for container '%s'\n", "running", out, cid) 2079 } 2080 if _, err := s.d.Cmd("kill", cid); err != nil { 2081 t.Fatal(err) 2082 } 2083 } 2084 2085 // TestRunLinksChanged checks that creating a new container with the same name does not update links 2086 // this ensures that the old, pre gh#16032 functionality continues on 2087 func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) { 2088 testRequires(c, DaemonIsLinux) // Windows does not support links 2089 s.d.StartWithBusybox(c) 2090 2091 out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") 2092 c.Assert(err, check.IsNil, check.Commentf(out)) 2093 2094 out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc") 2095 c.Assert(err, check.IsNil, check.Commentf(out)) 2096 c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received") 2097 2098 out, err = s.d.Cmd("rm", "-f", "test") 2099 c.Assert(err, check.IsNil, check.Commentf(out)) 2100 2101 out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top") 2102 c.Assert(err, check.IsNil, check.Commentf(out)) 2103 out, err = s.d.Cmd("start", "-a", "test2") 2104 c.Assert(err, check.NotNil, check.Commentf(out)) 2105 c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received") 2106 2107 s.d.Restart(c) 2108 out, err = s.d.Cmd("start", "-a", "test2") 2109 c.Assert(err, check.NotNil, check.Commentf(out)) 2110 c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received") 2111 } 2112 2113 func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) { 2114 testRequires(c, DaemonIsLinux, NotPpc64le) 2115 2116 infoLog := "\x1b[34mINFO\x1b" 2117 2118 b := bytes.NewBuffer(nil) 2119 done := make(chan bool) 2120 2121 p, tty, err := pty.Open() 2122 c.Assert(err, checker.IsNil) 2123 defer func() { 2124 tty.Close() 2125 p.Close() 2126 }() 2127 2128 go func() { 2129 io.Copy(b, p) 2130 done <- true 2131 }() 2132 2133 // Enable coloring explicitly 2134 s.d.StartWithLogFile(tty, "--raw-logs=false") 2135 s.d.Stop(c) 2136 // Wait for io.Copy() before checking output 2137 <-done 2138 c.Assert(b.String(), checker.Contains, infoLog) 2139 2140 b.Reset() 2141 2142 // "tty" is already closed in prev s.d.Stop(), 2143 // we have to close the other side "p" and open another pair of 2144 // pty for the next test. 2145 p.Close() 2146 p, tty, err = pty.Open() 2147 c.Assert(err, checker.IsNil) 2148 2149 go func() { 2150 io.Copy(b, p) 2151 done <- true 2152 }() 2153 2154 // Disable coloring explicitly 2155 s.d.StartWithLogFile(tty, "--raw-logs=true") 2156 s.d.Stop(c) 2157 // Wait for io.Copy() before checking output 2158 <-done 2159 c.Assert(b.String(), check.Not(check.Equals), "") 2160 c.Assert(b.String(), check.Not(checker.Contains), infoLog) 2161 } 2162 2163 func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) { 2164 testRequires(c, DaemonIsLinux, NotPpc64le) 2165 2166 debugLog := "\x1b[37mDEBU\x1b" 2167 2168 p, tty, err := pty.Open() 2169 c.Assert(err, checker.IsNil) 2170 defer func() { 2171 tty.Close() 2172 p.Close() 2173 }() 2174 2175 b := bytes.NewBuffer(nil) 2176 go io.Copy(b, p) 2177 2178 s.d.StartWithLogFile(tty, "--debug") 2179 s.d.Stop(c) 2180 c.Assert(b.String(), checker.Contains, debugLog) 2181 } 2182 2183 func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) { 2184 testRequires(c, SameHostDaemon, DaemonIsLinux) 2185 2186 // daemon config file 2187 daemonConfig := `{ "debug" : false }` 2188 configFile, err := ioutil.TempFile("", "test-daemon-discovery-backend-config-reload-config") 2189 c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload")) 2190 configFilePath := configFile.Name() 2191 defer func() { 2192 configFile.Close() 2193 os.RemoveAll(configFile.Name()) 2194 }() 2195 2196 _, err = configFile.Write([]byte(daemonConfig)) 2197 c.Assert(err, checker.IsNil) 2198 2199 // --log-level needs to be set so that d.Start() doesn't add --debug causing 2200 // a conflict with the config 2201 s.d.Start(c, "--config-file", configFilePath, "--log-level=info") 2202 2203 // daemon config file 2204 daemonConfig = `{ 2205 "cluster-store": "consul://consuladdr:consulport/some/path", 2206 "cluster-advertise": "192.168.56.100:0", 2207 "debug" : false 2208 }` 2209 2210 err = configFile.Truncate(0) 2211 c.Assert(err, checker.IsNil) 2212 _, err = configFile.Seek(0, os.SEEK_SET) 2213 c.Assert(err, checker.IsNil) 2214 2215 _, err = configFile.Write([]byte(daemonConfig)) 2216 c.Assert(err, checker.IsNil) 2217 2218 err = s.d.ReloadConfig() 2219 c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config")) 2220 2221 out, err := s.d.Cmd("info") 2222 c.Assert(err, checker.IsNil) 2223 2224 c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path")) 2225 c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0")) 2226 } 2227 2228 // Test for #21956 2229 func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) { 2230 s.d.StartWithBusybox(c, "--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514") 2231 2232 out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top") 2233 c.Assert(err, check.IsNil, check.Commentf(out)) 2234 id := strings.TrimSpace(out) 2235 2236 out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id) 2237 c.Assert(err, check.IsNil, check.Commentf(out)) 2238 c.Assert(out, checker.Contains, "{json-file map[]}") 2239 } 2240 2241 // Test case for #20936, #22443 2242 func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) { 2243 s.d.Start(c, "--max-concurrent-uploads=6", "--max-concurrent-downloads=8") 2244 2245 expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"` 2246 expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` 2247 content, err := s.d.ReadLogFile() 2248 c.Assert(err, checker.IsNil) 2249 c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) 2250 c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) 2251 } 2252 2253 // Test case for #20936, #22443 2254 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { 2255 testRequires(c, SameHostDaemon, DaemonIsLinux) 2256 2257 // daemon config file 2258 configFilePath := "test.json" 2259 configFile, err := os.Create(configFilePath) 2260 c.Assert(err, checker.IsNil) 2261 defer os.Remove(configFilePath) 2262 2263 daemonConfig := `{ "max-concurrent-downloads" : 8 }` 2264 fmt.Fprintf(configFile, "%s", daemonConfig) 2265 configFile.Close() 2266 s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) 2267 2268 expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` 2269 expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` 2270 content, err := s.d.ReadLogFile() 2271 c.Assert(err, checker.IsNil) 2272 c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) 2273 c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) 2274 2275 configFile, err = os.Create(configFilePath) 2276 c.Assert(err, checker.IsNil) 2277 daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }` 2278 fmt.Fprintf(configFile, "%s", daemonConfig) 2279 configFile.Close() 2280 2281 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2282 // syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP) 2283 2284 time.Sleep(3 * time.Second) 2285 2286 expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"` 2287 expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"` 2288 content, err = s.d.ReadLogFile() 2289 c.Assert(err, checker.IsNil) 2290 c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) 2291 c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) 2292 } 2293 2294 // Test case for #20936, #22443 2295 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) { 2296 testRequires(c, SameHostDaemon, DaemonIsLinux) 2297 2298 // daemon config file 2299 configFilePath := "test.json" 2300 configFile, err := os.Create(configFilePath) 2301 c.Assert(err, checker.IsNil) 2302 defer os.Remove(configFilePath) 2303 2304 daemonConfig := `{ "max-concurrent-uploads" : null }` 2305 fmt.Fprintf(configFile, "%s", daemonConfig) 2306 configFile.Close() 2307 s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) 2308 2309 expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` 2310 expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"` 2311 content, err := s.d.ReadLogFile() 2312 c.Assert(err, checker.IsNil) 2313 c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) 2314 c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) 2315 2316 configFile, err = os.Create(configFilePath) 2317 c.Assert(err, checker.IsNil) 2318 daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }` 2319 fmt.Fprintf(configFile, "%s", daemonConfig) 2320 configFile.Close() 2321 2322 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2323 // syscall.Kill(s.d.cmd.Process.Pid, syscall.SIGHUP) 2324 2325 time.Sleep(3 * time.Second) 2326 2327 expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"` 2328 expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` 2329 content, err = s.d.ReadLogFile() 2330 c.Assert(err, checker.IsNil) 2331 c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) 2332 c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) 2333 2334 configFile, err = os.Create(configFilePath) 2335 c.Assert(err, checker.IsNil) 2336 daemonConfig = `{ "labels":["foo=bar"] }` 2337 fmt.Fprintf(configFile, "%s", daemonConfig) 2338 configFile.Close() 2339 2340 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2341 2342 time.Sleep(3 * time.Second) 2343 2344 expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"` 2345 expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` 2346 content, err = s.d.ReadLogFile() 2347 c.Assert(err, checker.IsNil) 2348 c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) 2349 c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) 2350 } 2351 2352 func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) { 2353 s.d.StartWithBusybox(c, "-b=none", "--iptables=false") 2354 out, code, err := s.d.BuildImageWithOut("busyboxs", 2355 `FROM busybox 2356 RUN cat /etc/hosts`, false) 2357 comment := check.Commentf("Failed to build image. output %s, exitCode %d, err %v", out, code, err) 2358 c.Assert(err, check.IsNil, comment) 2359 c.Assert(code, check.Equals, 0, comment) 2360 } 2361 2362 // Test case for #21976 2363 func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *check.C) { 2364 testRequires(c, SameHostDaemon, DaemonIsLinux) 2365 2366 s.d.StartWithBusybox(c, "--dns", "1.2.3.4", "--dns-search", "example.com", "--dns-opt", "timeout:3") 2367 2368 expectedOutput := "nameserver 1.2.3.4" 2369 out, _ := s.d.Cmd("run", "--net=host", "busybox", "cat", "/etc/resolv.conf") 2370 c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) 2371 expectedOutput = "search example.com" 2372 c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) 2373 expectedOutput = "options timeout:3" 2374 c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) 2375 } 2376 2377 func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { 2378 conf, err := ioutil.TempFile("", "config-file-") 2379 c.Assert(err, check.IsNil) 2380 configName := conf.Name() 2381 conf.Close() 2382 defer os.Remove(configName) 2383 2384 config := ` 2385 { 2386 "runtimes": { 2387 "oci": { 2388 "path": "docker-runc" 2389 }, 2390 "vm": { 2391 "path": "/usr/local/bin/vm-manager", 2392 "runtimeArgs": [ 2393 "--debug" 2394 ] 2395 } 2396 } 2397 } 2398 ` 2399 ioutil.WriteFile(configName, []byte(config), 0644) 2400 s.d.StartWithBusybox(c, "--config-file", configName) 2401 2402 // Run with default runtime 2403 out, err := s.d.Cmd("run", "--rm", "busybox", "ls") 2404 c.Assert(err, check.IsNil, check.Commentf(out)) 2405 2406 // Run with default runtime explicitly 2407 out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") 2408 c.Assert(err, check.IsNil, check.Commentf(out)) 2409 2410 // Run with oci (same path as default) but keep it around 2411 out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") 2412 c.Assert(err, check.IsNil, check.Commentf(out)) 2413 2414 // Run with "vm" 2415 out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") 2416 c.Assert(err, check.NotNil, check.Commentf(out)) 2417 c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") 2418 2419 // Reset config to only have the default 2420 config = ` 2421 { 2422 "runtimes": { 2423 } 2424 } 2425 ` 2426 ioutil.WriteFile(configName, []byte(config), 0644) 2427 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2428 // Give daemon time to reload config 2429 <-time.After(1 * time.Second) 2430 2431 // Run with default runtime 2432 out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") 2433 c.Assert(err, check.IsNil, check.Commentf(out)) 2434 2435 // Run with "oci" 2436 out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") 2437 c.Assert(err, check.NotNil, check.Commentf(out)) 2438 c.Assert(out, checker.Contains, "Unknown runtime specified oci") 2439 2440 // Start previously created container with oci 2441 out, err = s.d.Cmd("start", "oci-runtime-ls") 2442 c.Assert(err, check.NotNil, check.Commentf(out)) 2443 c.Assert(out, checker.Contains, "Unknown runtime specified oci") 2444 2445 // Check that we can't override the default runtime 2446 config = ` 2447 { 2448 "runtimes": { 2449 "runc": { 2450 "path": "my-runc" 2451 } 2452 } 2453 } 2454 ` 2455 ioutil.WriteFile(configName, []byte(config), 0644) 2456 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2457 // Give daemon time to reload config 2458 <-time.After(1 * time.Second) 2459 2460 content, err := s.d.ReadLogFile() 2461 c.Assert(err, checker.IsNil) 2462 c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`) 2463 2464 // Check that we can select a default runtime 2465 config = ` 2466 { 2467 "default-runtime": "vm", 2468 "runtimes": { 2469 "oci": { 2470 "path": "docker-runc" 2471 }, 2472 "vm": { 2473 "path": "/usr/local/bin/vm-manager", 2474 "runtimeArgs": [ 2475 "--debug" 2476 ] 2477 } 2478 } 2479 } 2480 ` 2481 ioutil.WriteFile(configName, []byte(config), 0644) 2482 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2483 // Give daemon time to reload config 2484 <-time.After(1 * time.Second) 2485 2486 out, err = s.d.Cmd("run", "--rm", "busybox", "ls") 2487 c.Assert(err, check.NotNil, check.Commentf(out)) 2488 c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") 2489 2490 // Run with default runtime explicitly 2491 out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") 2492 c.Assert(err, check.IsNil, check.Commentf(out)) 2493 } 2494 2495 func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { 2496 s.d.StartWithBusybox(c, "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") 2497 2498 // Run with default runtime 2499 out, err := s.d.Cmd("run", "--rm", "busybox", "ls") 2500 c.Assert(err, check.IsNil, check.Commentf(out)) 2501 2502 // Run with default runtime explicitly 2503 out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") 2504 c.Assert(err, check.IsNil, check.Commentf(out)) 2505 2506 // Run with oci (same path as default) but keep it around 2507 out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") 2508 c.Assert(err, check.IsNil, check.Commentf(out)) 2509 2510 // Run with "vm" 2511 out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") 2512 c.Assert(err, check.NotNil, check.Commentf(out)) 2513 c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") 2514 2515 // Start a daemon without any extra runtimes 2516 s.d.Stop(c) 2517 s.d.StartWithBusybox(c) 2518 2519 // Run with default runtime 2520 out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") 2521 c.Assert(err, check.IsNil, check.Commentf(out)) 2522 2523 // Run with "oci" 2524 out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") 2525 c.Assert(err, check.NotNil, check.Commentf(out)) 2526 c.Assert(out, checker.Contains, "Unknown runtime specified oci") 2527 2528 // Start previously created container with oci 2529 out, err = s.d.Cmd("start", "oci-runtime-ls") 2530 c.Assert(err, check.NotNil, check.Commentf(out)) 2531 c.Assert(out, checker.Contains, "Unknown runtime specified oci") 2532 2533 // Check that we can't override the default runtime 2534 s.d.Stop(c) 2535 c.Assert(s.d.StartWithError("--add-runtime", "runc=my-runc"), checker.NotNil) 2536 2537 content, err := s.d.ReadLogFile() 2538 c.Assert(err, checker.IsNil) 2539 c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`) 2540 2541 // Check that we can select a default runtime 2542 s.d.Stop(c) 2543 s.d.StartWithBusybox(c, "--default-runtime=vm", "--add-runtime", "oci=docker-runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") 2544 2545 out, err = s.d.Cmd("run", "--rm", "busybox", "ls") 2546 c.Assert(err, check.NotNil, check.Commentf(out)) 2547 c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") 2548 2549 // Run with default runtime explicitly 2550 out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") 2551 c.Assert(err, check.IsNil, check.Commentf(out)) 2552 } 2553 2554 func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) { 2555 s.d.StartWithBusybox(c) 2556 2557 // top1 will exist after daemon restarts 2558 out, err := s.d.Cmd("run", "-d", "--name", "top1", "busybox:latest", "top") 2559 c.Assert(err, checker.IsNil, check.Commentf("run top1: %v", out)) 2560 // top2 will be removed after daemon restarts 2561 out, err = s.d.Cmd("run", "-d", "--rm", "--name", "top2", "busybox:latest", "top") 2562 c.Assert(err, checker.IsNil, check.Commentf("run top2: %v", out)) 2563 2564 out, err = s.d.Cmd("ps") 2565 c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should be running")) 2566 c.Assert(out, checker.Contains, "top2", check.Commentf("top2 should be running")) 2567 2568 // now restart daemon gracefully 2569 s.d.Restart(c) 2570 2571 out, err = s.d.Cmd("ps", "-a") 2572 c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) 2573 c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should exist after daemon restarts")) 2574 c.Assert(out, checker.Not(checker.Contains), "top2", check.Commentf("top2 should be removed after daemon restarts")) 2575 } 2576 2577 func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) { 2578 s.d.StartWithBusybox(c) 2579 2580 containerName := "error-values" 2581 // Make a container with both a non 0 exit code and an error message 2582 // We explicitly disable `--init` for this test, because `--init` is enabled by default 2583 // on "experimental". Enabling `--init` results in a different behavior; because the "init" 2584 // process itself is PID1, the container does not fail on _startup_ (i.e., `docker-init` starting), 2585 // but directly after. The exit code of the container is still 127, but the Error Message is not 2586 // captured, so `.State.Error` is empty. 2587 // See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426, 2588 // and https://github.com/docker/docker/pull/26061#r78054578 for more information. 2589 out, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto") 2590 c.Assert(err, checker.NotNil) 2591 2592 // Check that those values were saved on disk 2593 out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) 2594 out = strings.TrimSpace(out) 2595 c.Assert(err, checker.IsNil) 2596 c.Assert(out, checker.Equals, "127") 2597 2598 errMsg1, err := s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) 2599 errMsg1 = strings.TrimSpace(errMsg1) 2600 c.Assert(err, checker.IsNil) 2601 c.Assert(errMsg1, checker.Contains, "executable file not found") 2602 2603 // now restart daemon 2604 s.d.Restart(c) 2605 2606 // Check that those values are still around 2607 out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) 2608 out = strings.TrimSpace(out) 2609 c.Assert(err, checker.IsNil) 2610 c.Assert(out, checker.Equals, "127") 2611 2612 out, err = s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) 2613 out = strings.TrimSpace(out) 2614 c.Assert(err, checker.IsNil) 2615 c.Assert(out, checker.Equals, errMsg1) 2616 } 2617 2618 func (s *DockerDaemonSuite) TestDaemonBackcompatPre17Volumes(c *check.C) { 2619 testRequires(c, SameHostDaemon) 2620 d := s.d 2621 d.StartWithBusybox(c) 2622 2623 // hack to be able to side-load a container config 2624 out, err := d.Cmd("create", "busybox:latest") 2625 c.Assert(err, checker.IsNil, check.Commentf(out)) 2626 id := strings.TrimSpace(out) 2627 2628 out, err = d.Cmd("inspect", "--type=image", "--format={{.ID}}", "busybox:latest") 2629 c.Assert(err, checker.IsNil, check.Commentf(out)) 2630 d.Stop(c) 2631 <-d.Wait 2632 2633 imageID := strings.TrimSpace(out) 2634 volumeID := stringid.GenerateNonCryptoID() 2635 vfsPath := filepath.Join(d.Root, "vfs", "dir", volumeID) 2636 c.Assert(os.MkdirAll(vfsPath, 0755), checker.IsNil) 2637 2638 config := []byte(` 2639 { 2640 "ID": "` + id + `", 2641 "Name": "hello", 2642 "Driver": "` + d.StorageDriver() + `", 2643 "Image": "` + imageID + `", 2644 "Config": {"Image": "busybox:latest"}, 2645 "NetworkSettings": {}, 2646 "Volumes": { 2647 "/bar":"/foo", 2648 "/foo": "` + vfsPath + `", 2649 "/quux":"/quux" 2650 }, 2651 "VolumesRW": { 2652 "/bar": true, 2653 "/foo": true, 2654 "/quux": false 2655 } 2656 } 2657 `) 2658 2659 configPath := filepath.Join(d.Root, "containers", id, "config.v2.json") 2660 err = ioutil.WriteFile(configPath, config, 600) 2661 d.Start(c) 2662 2663 out, err = d.Cmd("inspect", "--type=container", "--format={{ json .Mounts }}", id) 2664 c.Assert(err, checker.IsNil, check.Commentf(out)) 2665 type mount struct { 2666 Name string 2667 Source string 2668 Destination string 2669 Driver string 2670 RW bool 2671 } 2672 2673 ls := []mount{} 2674 err = json.NewDecoder(strings.NewReader(out)).Decode(&ls) 2675 c.Assert(err, checker.IsNil) 2676 2677 expected := []mount{ 2678 {Source: "/foo", Destination: "/bar", RW: true}, 2679 {Name: volumeID, Destination: "/foo", RW: true}, 2680 {Source: "/quux", Destination: "/quux", RW: false}, 2681 } 2682 c.Assert(ls, checker.HasLen, len(expected)) 2683 2684 for _, m := range ls { 2685 var matched bool 2686 for _, x := range expected { 2687 if m.Source == x.Source && m.Destination == x.Destination && m.RW == x.RW || m.Name != x.Name { 2688 matched = true 2689 break 2690 } 2691 } 2692 c.Assert(matched, checker.True, check.Commentf("did find match for %+v", m)) 2693 } 2694 } 2695 2696 func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) { 2697 testRequires(c, SameHostDaemon, DaemonIsLinux) 2698 2699 dockerProxyPath, err := exec.LookPath("docker-proxy") 2700 c.Assert(err, checker.IsNil) 2701 tmpDir, err := ioutil.TempDir("", "test-docker-proxy") 2702 c.Assert(err, checker.IsNil) 2703 2704 newProxyPath := filepath.Join(tmpDir, "docker-proxy") 2705 cmd := exec.Command("cp", dockerProxyPath, newProxyPath) 2706 c.Assert(cmd.Run(), checker.IsNil) 2707 2708 // custom one 2709 s.d.StartWithBusybox(c, "--userland-proxy-path", newProxyPath) 2710 out, err := s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") 2711 c.Assert(err, checker.IsNil, check.Commentf(out)) 2712 2713 // try with the original one 2714 s.d.Restart(c, "--userland-proxy-path", dockerProxyPath) 2715 out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") 2716 c.Assert(err, checker.IsNil, check.Commentf(out)) 2717 2718 // not exist 2719 s.d.Restart(c, "--userland-proxy-path", "/does/not/exist") 2720 out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") 2721 c.Assert(err, checker.NotNil, check.Commentf(out)) 2722 c.Assert(out, checker.Contains, "driver failed programming external connectivity on endpoint") 2723 c.Assert(out, checker.Contains, "/does/not/exist: no such file or directory") 2724 } 2725 2726 // Test case for #22471 2727 func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) { 2728 testRequires(c, SameHostDaemon) 2729 s.d.StartWithBusybox(c, "--shutdown-timeout=3") 2730 2731 _, err := s.d.Cmd("run", "-d", "busybox", "top") 2732 c.Assert(err, check.IsNil) 2733 2734 c.Assert(s.d.Signal(syscall.SIGINT), checker.IsNil) 2735 2736 select { 2737 case <-s.d.Wait: 2738 case <-time.After(5 * time.Second): 2739 } 2740 2741 expectedMessage := `level=debug msg="start clean shutdown of all containers with a 3 seconds timeout..."` 2742 content, err := s.d.ReadLogFile() 2743 c.Assert(err, checker.IsNil) 2744 c.Assert(string(content), checker.Contains, expectedMessage) 2745 } 2746 2747 // Test case for #22471 2748 func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) { 2749 testRequires(c, SameHostDaemon) 2750 2751 // daemon config file 2752 configFilePath := "test.json" 2753 configFile, err := os.Create(configFilePath) 2754 c.Assert(err, checker.IsNil) 2755 defer os.Remove(configFilePath) 2756 2757 daemonConfig := `{ "shutdown-timeout" : 8 }` 2758 fmt.Fprintf(configFile, "%s", daemonConfig) 2759 configFile.Close() 2760 s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) 2761 2762 configFile, err = os.Create(configFilePath) 2763 c.Assert(err, checker.IsNil) 2764 daemonConfig = `{ "shutdown-timeout" : 5 }` 2765 fmt.Fprintf(configFile, "%s", daemonConfig) 2766 configFile.Close() 2767 2768 c.Assert(s.d.Signal(syscall.SIGHUP), checker.IsNil) 2769 2770 select { 2771 case <-s.d.Wait: 2772 case <-time.After(3 * time.Second): 2773 } 2774 2775 expectedMessage := `level=debug msg="Reset Shutdown Timeout: 5"` 2776 content, err := s.d.ReadLogFile() 2777 c.Assert(err, checker.IsNil) 2778 c.Assert(string(content), checker.Contains, expectedMessage) 2779 } 2780 2781 // Test case for 29342 2782 func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) { 2783 testRequires(c, DaemonIsLinux) 2784 s.d.StartWithBusybox(c, "--live-restore") 2785 2786 out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "sh", "-c", "addgroup -S test && adduser -S -G test test -D -s /bin/sh && top") 2787 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2788 2789 s.d.WaitRun("top") 2790 2791 out1, err := s.d.Cmd("exec", "-u", "test", "top", "id") 2792 // uid=100(test) gid=101(test) groups=101(test) 2793 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out1)) 2794 2795 // restart daemon. 2796 s.d.Restart(c, "--live-restore") 2797 2798 out2, err := s.d.Cmd("exec", "-u", "test", "top", "id") 2799 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out2)) 2800 c.Assert(out1, check.Equals, out2, check.Commentf("Output: before restart '%s', after restart '%s'", out1, out2)) 2801 2802 out, err = s.d.Cmd("stop", "top") 2803 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2804 } 2805 2806 func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { 2807 testRequires(c, DaemonIsLinux, overlayFSSupported, SameHostDaemon) 2808 s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay") 2809 out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top") 2810 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2811 2812 s.d.WaitRun("top") 2813 2814 // restart daemon. 2815 s.d.Restart(c, "--live-restore", "--storage-driver", "overlay") 2816 2817 out, err = s.d.Cmd("stop", "top") 2818 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2819 2820 // test if the rootfs mountpoint still exist 2821 mountpoint, err := s.d.InspectField("top", ".GraphDriver.Data.MergedDir") 2822 c.Assert(err, check.IsNil) 2823 f, err := os.Open("/proc/self/mountinfo") 2824 c.Assert(err, check.IsNil) 2825 defer f.Close() 2826 sc := bufio.NewScanner(f) 2827 for sc.Scan() { 2828 line := sc.Text() 2829 if strings.Contains(line, mountpoint) { 2830 c.Fatalf("mountinfo should not include the mountpoint of stop container") 2831 } 2832 } 2833 2834 out, err = s.d.Cmd("rm", "top") 2835 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2836 } 2837 2838 // #29598 2839 func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { 2840 testRequires(c, DaemonIsLinux, SameHostDaemon) 2841 s.d.StartWithBusybox(c, "--live-restore") 2842 2843 out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") 2844 c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) 2845 id := strings.TrimSpace(out) 2846 2847 type state struct { 2848 Running bool 2849 StartedAt time.Time 2850 } 2851 out, err = s.d.Cmd("inspect", "-f", "{{json .State}}", id) 2852 c.Assert(err, checker.IsNil, check.Commentf("output: %s", out)) 2853 2854 var origState state 2855 err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState) 2856 c.Assert(err, checker.IsNil) 2857 2858 s.d.Restart(c, "--live-restore") 2859 2860 pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id) 2861 c.Assert(err, check.IsNil) 2862 pidint, err := strconv.Atoi(strings.TrimSpace(pid)) 2863 c.Assert(err, check.IsNil) 2864 c.Assert(pidint, checker.GreaterThan, 0) 2865 c.Assert(syscall.Kill(pidint, syscall.SIGKILL), check.IsNil) 2866 2867 ticker := time.NewTicker(50 * time.Millisecond) 2868 timeout := time.After(10 * time.Second) 2869 2870 for range ticker.C { 2871 select { 2872 case <-timeout: 2873 c.Fatal("timeout waiting for container restart") 2874 default: 2875 } 2876 2877 out, err := s.d.Cmd("inspect", "-f", "{{json .State}}", id) 2878 c.Assert(err, checker.IsNil, check.Commentf("output: %s", out)) 2879 2880 var newState state 2881 err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState) 2882 c.Assert(err, checker.IsNil) 2883 2884 if !newState.Running { 2885 continue 2886 } 2887 if newState.StartedAt.After(origState.StartedAt) { 2888 break 2889 } 2890 } 2891 2892 out, err = s.d.Cmd("stop", id) 2893 c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) 2894 } 2895 2896 func (s *DockerDaemonSuite) TestShmSize(c *check.C) { 2897 testRequires(c, DaemonIsLinux) 2898 2899 size := 67108864 * 2 2900 pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) 2901 2902 s.d.StartWithBusybox(c, "--default-shm-size", fmt.Sprintf("%v", size)) 2903 2904 name := "shm1" 2905 out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") 2906 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2907 c.Assert(pattern.MatchString(out), checker.True) 2908 out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) 2909 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2910 c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) 2911 } 2912 2913 func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) { 2914 testRequires(c, DaemonIsLinux) 2915 2916 configPath, err := ioutil.TempDir("", "test-daemon-shm-size-reload-config") 2917 c.Assert(err, checker.IsNil, check.Commentf("could not create temp file for config reload")) 2918 defer os.RemoveAll(configPath) // clean up 2919 configFile := filepath.Join(configPath, "config.json") 2920 2921 size := 67108864 * 2 2922 configData := []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) 2923 c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload")) 2924 pattern := regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) 2925 2926 s.d.StartWithBusybox(c, "--config-file", configFile) 2927 2928 name := "shm1" 2929 out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") 2930 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2931 c.Assert(pattern.MatchString(out), checker.True) 2932 out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) 2933 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2934 c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) 2935 2936 size = 67108864 * 3 2937 configData = []byte(fmt.Sprintf(`{"default-shm-size": "%dM"}`, size/1024/1024)) 2938 c.Assert(ioutil.WriteFile(configFile, configData, 0666), checker.IsNil, check.Commentf("could not write temp file for config reload")) 2939 pattern = regexp.MustCompile(fmt.Sprintf("shm on /dev/shm type tmpfs(.*)size=%dk", size/1024)) 2940 2941 err = s.d.ReloadConfig() 2942 c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config")) 2943 2944 name = "shm2" 2945 out, err = s.d.Cmd("run", "--name", name, "busybox", "mount") 2946 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2947 c.Assert(pattern.MatchString(out), checker.True) 2948 out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) 2949 c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) 2950 c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) 2951 }