docker_cli_nat_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "os/exec"
  7. "testing"
  8. "github.com/dotcloud/docker/daemon"
  9. )
  10. func TestNetworkNat(t *testing.T) {
  11. iface, err := net.InterfaceByName("eth0")
  12. if err != nil {
  13. t.Skip("Test not running with `make test`. Interface eth0 not found: %s", err)
  14. }
  15. ifaceAddrs, err := iface.Addrs()
  16. if err != nil || len(ifaceAddrs) == 0 {
  17. t.Fatalf("Error retrieving addresses for eth0: %v (%d addresses)", err, len(ifaceAddrs))
  18. }
  19. ifaceIp, _, err := net.ParseCIDR(ifaceAddrs[0].String())
  20. if err != nil {
  21. t.Fatalf("Error retrieving the up for eth0: %s", err)
  22. }
  23. runCmd := exec.Command(dockerBinary, "run", "-d", "-p", "8080", "busybox", "nc", "-lp", "8080")
  24. out, _, err := runCommandWithOutput(runCmd)
  25. errorOut(err, t, fmt.Sprintf("run1 failed with errors: %v (%s)", err, out))
  26. cleanedContainerID := stripTrailingCharacters(out)
  27. inspectCmd := exec.Command(dockerBinary, "inspect", cleanedContainerID)
  28. inspectOut, _, err := runCommandWithOutput(inspectCmd)
  29. errorOut(err, t, fmt.Sprintf("out should've been a container id: %v %v", inspectOut, err))
  30. containers := []*daemon.Container{}
  31. if err := json.Unmarshal([]byte(inspectOut), &containers); err != nil {
  32. t.Fatalf("Error inspecting the container: %s", err)
  33. }
  34. if len(containers) != 1 {
  35. t.Fatalf("Unepexted container count. Expected 0, recieved: %d", len(containers))
  36. }
  37. port8080, exists := containers[0].NetworkSettings.Ports["8080/tcp"]
  38. if !exists || len(port8080) == 0 {
  39. t.Fatal("Port 8080/tcp not found in NetworkSettings")
  40. }
  41. runCmd = exec.Command(dockerBinary, "run", "-p", "8080", "busybox", "sh", "-c", fmt.Sprintf("echo hello world | nc -w 30 %s %s", ifaceIp, port8080[0].HostPort))
  42. out, _, err = runCommandWithOutput(runCmd)
  43. errorOut(err, t, fmt.Sprintf("run2 failed with errors: %v (%s)", err, out))
  44. runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
  45. out, _, err = runCommandWithOutput(runCmd)
  46. errorOut(err, t, fmt.Sprintf("failed to retrieve logs for container: %v %v", cleanedContainerID, err))
  47. if expected := "hello world\n"; out != expected {
  48. t.Fatalf("Unexpected output. Expected: %s, recieved: -->%s<--", expected, out)
  49. }
  50. killCmd := exec.Command(dockerBinary, "kill", cleanedContainerID)
  51. out, _, err = runCommandWithOutput(killCmd)
  52. errorOut(err, t, fmt.Sprintf("failed to kill container: %v %v", out, err))
  53. deleteAllContainers()
  54. logDone("network - make sure nat works through the host")
  55. }