Beispiel #1
0
func (s *DockerTrustSuite) TestTrustedPushWithExpiredSnapshot(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredsnapshot/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// Snapshots last for three years. This should be expired
	fourYearsLater := time.Now().Add(time.Hour * 24 * 365 * 4)

	runAtDifferentDate(fourYearsLater, func() {
		// Push with wrong passphrases
		pushCmd = exec.Command(dockerBinary, "push", repoName)
		s.trustedCmd(pushCmd)
		out, _, err = runCommandWithOutput(pushCmd)
		if err == nil {
			c.Fatalf("Error missing from trusted push with expired snapshot: \n%s", out)
		}

		if !strings.Contains(string(out), "repository out-of-date") {
			c.Fatalf("Missing expected output on trusted push with expired snapshot:\n%s", out)
		}
	})
}
// TestRunDeviceSymlink checks run with device that follows symlink (#13840)
func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
	if _, err := os.Stat("/dev/zero"); err != nil {
		c.Skip("Host does not have /dev/zero")
	}

	// Create a temporary directory to create symlink
	tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
	c.Assert(err, checker.IsNil)

	defer os.RemoveAll(tmpDir)

	// Create a symbolic link to /dev/zero
	symZero := filepath.Join(tmpDir, "zero")
	err = os.Symlink("/dev/zero", symZero)
	c.Assert(err, checker.IsNil)

	// Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
	// then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
	tmpFile := filepath.Join(tmpDir, "temp")
	err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
	c.Assert(err, checker.IsNil)
	symFile := filepath.Join(tmpDir, "file")
	err = os.Symlink(tmpFile, symFile)
	c.Assert(err, checker.IsNil)

	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
	out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))

	// symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
	out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
	c.Assert(err, check.NotNil)
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
}
Beispiel #3
0
func newTestRegistryV2(c *check.C) (*testRegistryV2, error) {
	template := `version: 0.1
loglevel: debug
storage:
    filesystem:
        rootdirectory: %s
http:
    addr: %s`
	tmp, err := ioutil.TempDir("", "registry-test-")
	if err != nil {
		return nil, err
	}
	confPath := filepath.Join(tmp, "config.yaml")
	config, err := os.Create(confPath)
	if err != nil {
		return nil, err
	}
	if _, err := fmt.Fprintf(config, template, tmp, privateRegistryURL); err != nil {
		os.RemoveAll(tmp)
		return nil, err
	}

	cmd := exec.Command(v2binary, confPath)
	if err := cmd.Start(); err != nil {
		os.RemoveAll(tmp)
		if os.IsNotExist(err) {
			c.Skip(err.Error())
		}
		return nil, err
	}
	return &testRegistryV2{
		cmd: cmd,
		dir: tmp,
	}, nil
}
Beispiel #4
0
func (s *DockerTrustSuite) TestTrustedPushWithExpiredTimestamp(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppush/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)
	if err != nil {
		c.Fatalf("trusted push failed: %s\n%s", err, out)
	}

	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
		c.Fatalf("Missing expected output on trusted push:\n%s", out)
	}

	// The timestamps expire in two weeks. Lets check three
	threeWeeksLater := time.Now().Add(time.Hour * 24 * 21)

	// Should succeed because the server transparently re-signs one
	runAtDifferentDate(threeWeeksLater, func() {
		pushCmd := exec.Command(dockerBinary, "push", repoName)
		s.trustedCmd(pushCmd)
		out, _, err := runCommandWithOutput(pushCmd)
		if err != nil {
			c.Fatalf("Error running trusted push: %s\n%s", err, out)
		}
		if !strings.Contains(string(out), "Signing and pushing trust metadata") {
			c.Fatalf("Missing expected output on trusted push with expired timestamp:\n%s", out)
		}
	})
}
func (s *DockerSuite) TestClientSetsTLSServerName(c *check.C) {
	c.Skip("Flakey test")
	// there may be more than one hit to the server for each registry request
	serverNameReceived := []string{}
	var serverName string

	virtualHostServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		serverNameReceived = append(serverNameReceived, r.TLS.ServerName)
	}))
	defer virtualHostServer.Close()
	// discard TLS handshake errors written by default to os.Stderr
	virtualHostServer.Config.ErrorLog = log.New(ioutil.Discard, "", 0)

	u, err := url.Parse(virtualHostServer.URL)
	c.Assert(err, check.IsNil)
	hostPort := u.Host
	serverName = strings.Split(hostPort, ":")[0]

	repoName := fmt.Sprintf("%v/dockercli/image:latest", hostPort)
	cmd := exec.Command(dockerBinary, "pull", repoName)
	cmd.Run()

	// check that the fake server was hit at least once
	c.Assert(len(serverNameReceived) > 0, check.Equals, true)
	// check that for each hit the right server name was received
	for _, item := range serverNameReceived {
		c.Check(item, check.Equals, serverName)
	}
}
func (s *DockerTrustSuite) TestPullWhenCertExpired(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := s.setupTrustedImage(c, "trusted-cert-expired")

	// Certificates have 10 years of expiration
	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)

	runAtDifferentDate(elevenYearsFromNow, func() {
		// Try pull
		pullCmd := exec.Command(dockerBinary, "pull", repoName)
		s.trustedCmd(pullCmd)
		out, _, err := runCommandWithOutput(pullCmd)
		if err == nil {
			c.Fatalf("Error running trusted pull in the distant future: %s\n%s", err, out)
		}

		if !strings.Contains(string(out), "could not validate the path to a trusted root") {
			c.Fatalf("Missing expected output on trusted pull in the distant future:\n%s", out)
		}
	})

	runAtDifferentDate(elevenYearsFromNow, func() {
		// Try pull
		pullCmd := exec.Command(dockerBinary, "pull", "--disable-content-trust", repoName)
		s.trustedCmd(pullCmd)
		out, _, err := runCommandWithOutput(pullCmd)
		if err != nil {
			c.Fatalf("Error running untrusted pull in the distant future: %s\n%s", err, out)
		}

		if !strings.Contains(string(out), "Status: Downloaded") {
			c.Fatalf("Missing expected output on untrusted pull in the distant future:\n%s", out)
		}
	})
}
// testRequires checks if the environment satisfies the requirements
// for the test to run or skips the tests.
func testRequires(c *check.C, requirements ...testRequirement) {
	for _, r := range requirements {
		if !r.Condition() {
			c.Skip(r.SkipMessage)
		}
	}
}
func (s *DockerSuite) TestPsListContainersFilterCreated(c *check.C) {
	// TODO Windows: Figure out why TestPsListContainers* are flakey
	if daemonPlatform == "windows" {
		c.Skip("Flaky on windowsTP4")
	}

	// create a container
	out, _ := dockerCmd(c, "create", "busybox")
	cID := strings.TrimSpace(out)
	shortCID := cID[:12]

	// Make sure it DOESN'T show up w/o a '-a' for normal 'ps'
	out, _ = dockerCmd(c, "ps", "-q")
	c.Assert(out, checker.Not(checker.Contains), shortCID, check.Commentf("Should have not seen '%s' in ps output:\n%s", shortCID, out))

	// Make sure it DOES show up as 'Created' for 'ps -a'
	out, _ = dockerCmd(c, "ps", "-a")

	hits := 0
	for _, line := range strings.Split(out, "\n") {
		if !strings.Contains(line, shortCID) {
			continue
		}
		hits++
		c.Assert(line, checker.Contains, "Created", check.Commentf("Missing 'Created' on '%s'", line))
	}

	c.Assert(hits, checker.Equals, 1, check.Commentf("Should have seen '%s' in ps -a output once:%d\n%s", shortCID, hits, out))

	// filter containers by 'create' - note, no -a needed
	out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created")
	containerOut := strings.TrimSpace(out)
	c.Assert(cID, checker.HasPrefix, containerOut)
}
func (s *DockerTrustSuite) TestTrustedPullWithExpiredSnapshot(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppull/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	pushCmd := exec.Command(dockerBinary, "push", repoName)
	s.trustedCmd(pushCmd)
	out, _, err := runCommandWithOutput(pushCmd)

	c.Assert(err, check.IsNil, check.Commentf(out))
	c.Assert(string(out), checker.Contains, "Signing and pushing trust metadata", check.Commentf(out))

	dockerCmd(c, "rmi", repoName)

	// Snapshots last for three years. This should be expired
	fourYearsLater := time.Now().Add(time.Hour * 24 * 365 * 4)

	runAtDifferentDate(fourYearsLater, func() {
		// Try pull
		pullCmd := exec.Command(dockerBinary, "pull", repoName)
		s.trustedCmd(pullCmd)
		out, _, err = runCommandWithOutput(pullCmd)

		c.Assert(err, check.NotNil, check.Commentf("Missing expected error running trusted pull with expired snapshots"))
		c.Assert(string(out), checker.Contains, "repository out-of-date", check.Commentf(out))
	})
}
func (s *DockerSuite) TestInspectBindMountPoint(c *check.C) {
	modifier := ",z"
	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
	if daemonPlatform == "windows" {
		modifier = ""
		// TODO Windows: Temporary check - remove once TP5 support is dropped
		if windowsDaemonKV < 14350 {
			c.Skip("Needs later Windows build for RO volumes")
		}
		// Linux creates the host directory if it doesn't exist. Windows does not.
		os.Mkdir(`c:\data`, os.ModeDir)
	}

	dockerCmd(c, "run", "-d", "--name", "test", "-v", prefix+slash+"data:"+prefix+slash+"data:ro"+modifier, "busybox", "cat")

	vol := inspectFieldJSON(c, "test", "Mounts")

	var mp []types.MountPoint
	err := unmarshalJSON([]byte(vol), &mp)
	c.Assert(err, checker.IsNil)

	// check that there is only one mountpoint
	c.Assert(mp, check.HasLen, 1)

	m := mp[0]

	c.Assert(m.Name, checker.Equals, "")
	c.Assert(m.Driver, checker.Equals, "")
	c.Assert(m.Source, checker.Equals, prefix+slash+"data")
	c.Assert(m.Destination, checker.Equals, prefix+slash+"data")
	c.Assert(m.Mode, checker.Equals, "ro"+modifier)
	c.Assert(m.RW, checker.Equals, false)
}
func (s *DockerTrustSuite) TestPullWhenCertExpired(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := s.setupTrustedImage(c, "trusted-cert-expired")

	// Certificates have 10 years of expiration
	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)

	testutil.RunAtDifferentDate(elevenYearsFromNow, func() {
		// Try pull
		pullCmd := exec.Command(dockerBinary, "pull", repoName)
		s.trustedCmd(pullCmd)
		out, _, err := runCommandWithOutput(pullCmd)

		c.Assert(err, check.NotNil, check.Commentf(out))
		c.Assert(string(out), checker.Contains, "could not validate the path to a trusted root", check.Commentf(out))
	})

	testutil.RunAtDifferentDate(elevenYearsFromNow, func() {
		// Try pull
		pullCmd := exec.Command(dockerBinary, "pull", "--disable-content-trust", repoName)
		s.trustedCmd(pullCmd)
		out, _, err := runCommandWithOutput(pullCmd)

		c.Assert(err, check.IsNil, check.Commentf(out))
		c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf(out))
	})
}
func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := s.setupTrustedImage(c, "trusted-create-expired")

	// Certificates have 10 years of expiration
	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)

	runAtDifferentDate(elevenYearsFromNow, func() {
		// Try create
		createCmd := exec.Command(dockerBinary, "create", repoName)
		s.trustedCmd(createCmd)
		out, _, err := runCommandWithOutput(createCmd)
		c.Assert(err, check.Not(check.IsNil))
		c.Assert(string(out), checker.Contains, "could not validate the path to a trusted root", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))
	})

	runAtDifferentDate(elevenYearsFromNow, func() {
		// Try create
		createCmd := exec.Command(dockerBinary, "create", "--disable-content-trust", repoName)
		s.trustedCmd(createCmd)
		out, _, err := runCommandWithOutput(createCmd)
		c.Assert(err, check.Not(check.IsNil))
		c.Assert(string(out), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", out))

	})
}
Beispiel #13
0
func (s *DockerTrustSuite) TestCreateWhenCertExpired(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := s.setupTrustedImage(c, "trusted-create-expired")

	// Certificates have 10 years of expiration
	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)

	testutil.RunAtDifferentDate(elevenYearsFromNow, func() {
		// Try create
		icmd.RunCmd(icmd.Cmd{
			Command: []string{dockerBinary, "create", repoName},
		}, trustedCmd).Assert(c, icmd.Expected{
			ExitCode: 1,
			Err:      "could not validate the path to a trusted root",
		})
	})

	testutil.RunAtDifferentDate(elevenYearsFromNow, func() {
		// Try create
		result := icmd.RunCmd(icmd.Command(dockerBinary, "create", "--disable-content-trust", repoName), trustedCmd)
		c.Assert(result.Error, check.Not(check.IsNil))
		c.Assert(string(result.Combined()), checker.Contains, "Status: Downloaded", check.Commentf("Missing expected output on trusted create in the distant future:\n%s", result.Combined()))

	})
}
func newTestNotary(c *check.C) (*testNotary, error) {
	template := `{
	"server": {
		"addr": "%s",
		"tls_key_file": "fixtures/notary/localhost.key",
		"tls_cert_file": "fixtures/notary/localhost.cert"
	},
	"trust_service": {
		"type": "local",
		"hostname": "",
		"port": "",
		"key_algorithm": "ed25519"
	},
	"logging": {
		"level": 5
	}
}`
	tmp, err := ioutil.TempDir("", "notary-test-")
	if err != nil {
		return nil, err
	}
	confPath := filepath.Join(tmp, "config.json")
	config, err := os.Create(confPath)
	if err != nil {
		return nil, err
	}
	if _, err := fmt.Fprintf(config, template, "localhost:4443"); err != nil {
		os.RemoveAll(tmp)
		return nil, err
	}

	cmd := exec.Command(notaryBinary, "-config", confPath)
	if err := cmd.Start(); err != nil {
		os.RemoveAll(tmp)
		if os.IsNotExist(err) {
			c.Skip(err.Error())
		}
		return nil, err
	}

	testNotary := &testNotary{
		cmd: cmd,
		dir: tmp,
	}

	// Wait for notary to be ready to serve requests.
	for i := 1; i <= 5; i++ {
		if err = testNotary.Ping(); err == nil {
			break
		}
		time.Sleep(10 * time.Millisecond * time.Duration(i*i))
	}

	if err != nil {
		c.Fatalf("Timeout waiting for test notary to become available: %s", err)
	}

	return testNotary, nil
}
func (s *DockerSwarmSuite) TestApiSwarmNodeDrainPause(c *check.C) {
	d1 := s.AddDaemon(c, true, true)
	d2 := s.AddDaemon(c, true, false)

	time.Sleep(1 * time.Second) // make sure all daemons are ready to accept tasks

	// start a service, expect balanced distribution
	instances := 8
	id := d1.createService(c, simpleTestService, setInstances(instances))

	waitAndAssert(c, defaultReconciliationTimeout, d1.checkActiveContainerCount, checker.GreaterThan, 0)
	waitAndAssert(c, defaultReconciliationTimeout, d2.checkActiveContainerCount, checker.GreaterThan, 0)
	waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.checkActiveContainerCount, d2.checkActiveContainerCount), checker.Equals, instances)

	// drain d2, all containers should move to d1
	d1.updateNode(c, d1.getNode(c, d2.NodeID), func(n *swarm.Node) {
		n.Spec.Availability = swarm.NodeAvailabilityDrain
	})
	waitAndAssert(c, defaultReconciliationTimeout, d1.checkActiveContainerCount, checker.Equals, instances)
	waitAndAssert(c, defaultReconciliationTimeout, d2.checkActiveContainerCount, checker.Equals, 0)

	// set d2 back to active
	d1.updateNode(c, d1.getNode(c, d2.NodeID), func(n *swarm.Node) {
		n.Spec.Availability = swarm.NodeAvailabilityActive
	})

	// change environment variable, resulting balanced rescheduling
	d1.updateService(c, d1.getService(c, id), func(s *swarm.Service) {
		s.Spec.TaskTemplate.ContainerSpec.Env = []string{"FOO=BAR"}
		s.Spec.UpdateConfig = &swarm.UpdateConfig{
			Parallelism: 2,
			Delay:       250 * time.Millisecond,
		}
	})

	// drained node first so we don't get any old containers
	waitAndAssert(c, defaultReconciliationTimeout, d2.checkActiveContainerCount, checker.GreaterThan, 0)
	waitAndAssert(c, defaultReconciliationTimeout, d1.checkActiveContainerCount, checker.GreaterThan, 0)
	waitAndAssert(c, defaultReconciliationTimeout*2, reducedCheck(sumAsIntegers, d1.checkActiveContainerCount, d2.checkActiveContainerCount), checker.Equals, instances)

	d2ContainerCount := len(d2.activeContainers())

	// set d2 to paused, scale service up, only d1 gets new tasks
	d1.updateNode(c, d1.getNode(c, d2.NodeID), func(n *swarm.Node) {
		n.Spec.Availability = swarm.NodeAvailabilityPause
	})

	c.Skip("known flakiness with scaling up from this state")

	instances = 14
	d1.updateService(c, d1.getService(c, id), setInstances(instances))

	waitAndAssert(c, defaultReconciliationTimeout, d1.checkActiveContainerCount, checker.Equals, instances-d2ContainerCount)
	waitAndAssert(c, defaultReconciliationTimeout, d2.checkActiveContainerCount, checker.Equals, d2ContainerCount)

}
func (s *DockerCmdSuite) TestDockerCmdWithTimeout(c *check.C) {
	c.Skip("racey test")
	cmds := []struct {
		binary           string
		args             []string
		timeout          time.Duration
		expectedOut      string
		expectedExitCode int
		expectedError    error
	}{
		{
			"doesnotexists",
			[]string{},
			5 * time.Millisecond,
			`Command doesnotexists not found.`,
			1,
			fmt.Errorf(`"" failed with errors: exit status 1 : "Command doesnotexists not found."`),
		},
		{
			dockerBinary,
			[]string{"an", "error"},
			5 * time.Millisecond,
			`an error has occurred`,
			1,
			fmt.Errorf(`"an error" failed with errors: exit status 1 : "an error has occurred"`),
		},
		{
			dockerBinary,
			[]string{"a", "command", "that", "times", "out"},
			5 * time.Millisecond,
			"",
			0,
			fmt.Errorf(`"a command that times out" failed with errors: command timed out : ""`),
		},
		{
			dockerBinary,
			[]string{"run", "-ti", "ubuntu", "echo", "hello"},
			5 * time.Millisecond,
			"hello",
			0,
			nil,
		},
	}
	for _, cmd := range cmds {
		out, exitCode, error := DockerCmdWithTimeout(cmd.binary, cmd.timeout, cmd.args...)
		c.Assert(out, check.Equals, cmd.expectedOut, check.Commentf("Expected output %q for arguments %v, got %q", cmd.expectedOut, cmd.args, out))
		c.Assert(exitCode, check.Equals, cmd.expectedExitCode, check.Commentf("Expected exitCode %q for arguments %v, got %q", cmd.expectedExitCode, cmd.args, exitCode))
		if cmd.expectedError != nil {
			c.Assert(error, check.NotNil, check.Commentf("Expected an error %q, got nothing", cmd.expectedError))
			c.Assert(error.Error(), check.Equals, cmd.expectedError.Error(), check.Commentf("Expected error %q for arguments %v, got %q", cmd.expectedError.Error(), cmd.args, error.Error()))
		} else {
			c.Assert(error, check.IsNil, check.Commentf("Expected no error, got %v", error))
		}
	}
}
func (s *DockerNetworkSuite) TestDockerNetworkMacvlanMultiSubnet(c *check.C) {
	// create a dual stack multi-subnet Macvlan bridge mode network and validate connectivity between four containers, two on each subnet
	testRequires(c, DaemonIsLinux, IPv6, MacvlanKernelSupport, NotUserNamespace, NotArm)
	dockerCmd(c, "network", "create", "--driver=macvlan", "--ipv6", "--subnet=172.28.100.0/24", "--subnet=172.28.102.0/24", "--gateway=172.28.102.254",
		"--subnet=2001:db8:abc2::/64", "--subnet=2001:db8:abc4::/64", "--gateway=2001:db8:abc4::254", "dualstackbridge")
	// Ensure the network was created
	assertNwIsAvailable(c, "dualstackbridge")
	// start dual stack containers and verify the user specified --ip and --ip6 addresses on subnets 172.28.100.0/24 and 2001:db8:abc2::/64
	dockerCmd(c, "run", "-d", "--net=dualstackbridge", "--name=first", "--ip", "172.28.100.20", "--ip6", "2001:db8:abc2::20", "busybox", "top")
	dockerCmd(c, "run", "-d", "--net=dualstackbridge", "--name=second", "--ip", "172.28.100.21", "--ip6", "2001:db8:abc2::21", "busybox", "top")

	// Inspect and store the v4 address from specified container on the network dualstackbridge
	ip := inspectField(c, "first", "NetworkSettings.Networks.dualstackbridge.IPAddress")
	// Inspect and store the v6 address from specified container on the network dualstackbridge
	ip6 := inspectField(c, "first", "NetworkSettings.Networks.dualstackbridge.GlobalIPv6Address")

	// verify ipv4 connectivity to the explicit --ipv address second to first
	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", strings.TrimSpace(ip))
	c.Assert(err, check.IsNil)
	// verify ipv6 connectivity to the explicit --ipv6 address second to first
	c.Skip("Temporarily skipping while invesitigating sporadic v6 CI issues")
	_, _, err = dockerCmdWithError("exec", "second", "ping6", "-c", "1", strings.TrimSpace(ip6))
	c.Assert(err, check.IsNil)

	// start dual stack containers and verify the user specified --ip and --ip6 addresses on subnets 172.28.102.0/24 and 2001:db8:abc4::/64
	dockerCmd(c, "run", "-d", "--net=dualstackbridge", "--name=third", "--ip", "172.28.102.20", "--ip6", "2001:db8:abc4::20", "busybox", "top")
	dockerCmd(c, "run", "-d", "--net=dualstackbridge", "--name=fourth", "--ip", "172.28.102.21", "--ip6", "2001:db8:abc4::21", "busybox", "top")

	// Inspect and store the v4 address from specified container on the network dualstackbridge
	ip = inspectField(c, "third", "NetworkSettings.Networks.dualstackbridge.IPAddress")
	// Inspect and store the v6 address from specified container on the network dualstackbridge
	ip6 = inspectField(c, "third", "NetworkSettings.Networks.dualstackbridge.GlobalIPv6Address")

	// verify ipv4 connectivity to the explicit --ipv address from third to fourth
	_, _, err = dockerCmdWithError("exec", "fourth", "ping", "-c", "1", strings.TrimSpace(ip))
	c.Assert(err, check.IsNil)
	// verify ipv6 connectivity to the explicit --ipv6 address from third to fourth
	_, _, err = dockerCmdWithError("exec", "fourth", "ping6", "-c", "1", strings.TrimSpace(ip6))
	c.Assert(err, check.IsNil)

	// Inspect the v4 gateway to ensure the proper default GW was assigned
	ip4gw := inspectField(c, "first", "NetworkSettings.Networks.dualstackbridge.Gateway")
	c.Assert(strings.TrimSpace(ip4gw), check.Equals, "172.28.100.1")
	// Inspect the v6 gateway to ensure the proper default GW was assigned
	ip6gw := inspectField(c, "first", "NetworkSettings.Networks.dualstackbridge.IPv6Gateway")
	c.Assert(strings.TrimSpace(ip6gw), check.Equals, "2001:db8:abc2::1")

	// Inspect the v4 gateway to ensure the proper explicitly assigned default GW was assigned
	ip4gw = inspectField(c, "third", "NetworkSettings.Networks.dualstackbridge.Gateway")
	c.Assert(strings.TrimSpace(ip4gw), check.Equals, "172.28.102.254")
	// Inspect the v6 gateway to ensure the proper explicitly assigned default GW was assigned
	ip6gw = inspectField(c, "third", "NetworkSettings.Networks.dualstackbridge.IPv6Gateway")
	c.Assert(strings.TrimSpace(ip6gw), check.Equals, "2001:db8:abc4::254")
}
func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
	if _, err := os.Stat("/dev/snd"); err != nil {
		c.Skip("Host does not have /dev/snd")
	}

	out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "timer", check.Commentf("expected output /dev/snd/timer"))

	out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "seq", check.Commentf("expected output /dev/othersnd/seq"))
}
func (s *DockerSuite) TestLinksEtcHostsContentMatch(c *check.C) {
	// In a _unix file as using Unix specific files, and must be on the
	// same host as the daemon.
	testRequires(c, SameHostDaemon, NotUserNamespace)

	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hosts")
	hosts, err := ioutil.ReadFile("/etc/hosts")
	if os.IsNotExist(err) {
		c.Skip("/etc/hosts does not exist, skip this test")
	}

	c.Assert(out, checker.Equals, string(hosts), check.Commentf("container: %s\n\nhost:%s", out, hosts))

}
func (s *DockerSuite) TestLinksEtcHostsContentMatch(c *check.C) {
	testRequires(c, SameHostDaemon)

	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hosts")
	hosts, err := ioutil.ReadFile("/etc/hosts")
	if os.IsNotExist(err) {
		c.Skip("/etc/hosts does not exist, skip this test")
	}

	if out != string(hosts) {
		c.Errorf("container: %s\n\nhost:%s", out, hosts)
	}

}
Beispiel #21
0
func (s *DockerSuite) TestNetworkNat(c *check.C) {
	testRequires(c, SameHostDaemon, NativeExecDriver)

	iface, err := net.InterfaceByName("eth0")
	if err != nil {
		c.Skip(fmt.Sprintf("Test not running with `make test`. Interface eth0 not found: %v", err))
	}

	ifaceAddrs, err := iface.Addrs()
	if err != nil || len(ifaceAddrs) == 0 {
		c.Fatalf("Error retrieving addresses for eth0: %v (%d addresses)", err, len(ifaceAddrs))
	}

	ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String())
	if err != nil {
		c.Fatalf("Error retrieving the up for eth0: %s", err)
	}

	runCmd := exec.Command(dockerBinary, "run", "-dt", "-p", "8080:8080", "busybox", "nc", "-lp", "8080")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	cleanedContainerID := strings.TrimSpace(out)

	runCmd = exec.Command(dockerBinary, "run", "busybox", "sh", "-c", fmt.Sprintf("echo hello world | nc -w 30 %s 8080", ifaceIP))
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	runCmd = exec.Command(dockerBinary, "logs", cleanedContainerID)
	out, _, err = runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatalf("failed to retrieve logs for container: %s, %v", out, err)
	}

	out = strings.Trim(out, "\r\n")

	if expected := "hello world"; out != expected {
		c.Fatalf("Unexpected output. Expected: %q, received: %q for iface %s", expected, out, ifaceIP)
	}

	killCmd := exec.Command(dockerBinary, "kill", cleanedContainerID)
	if out, _, err = runCommandWithOutput(killCmd); err != nil {
		c.Fatalf("failed to kill container: %s, %v", out, err)
	}

}
func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
	// TODO Windows. This requires further investigation for porting to
	// Windows CI. Currently fails.
	if daemonPlatform == "windows" {
		c.Skip("Fails on Windows CI")
	}
	name := "foo"

	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
	dir := prefix + slash + "home" + slash + "foo" + slash + "bar"

	dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
	dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
}
func getExternalAddress(c *check.C) net.IP {
	iface, err := net.InterfaceByName("eth0")
	if err != nil {
		c.Skip(fmt.Sprintf("Test not running with `make test`. Interface eth0 not found: %v", err))
	}

	ifaceAddrs, err := iface.Addrs()
	c.Assert(err, check.IsNil)
	c.Assert(ifaceAddrs, checker.Not(checker.HasLen), 0)

	ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String())
	c.Assert(err, check.IsNil)

	return ifaceIP
}
func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
	testRequires(c, DaemonIsLinux)

	fi, err := os.Stat("/dev/snd/timer")
	if err != nil {
		c.Skip("Host does not have /dev/snd/timer")
	}
	stat, ok := fi.Sys().(*syscall.Stat_t)
	if !ok {
		c.Skip("Could not stat /dev/snd/timer")
	}

	file := "/sys/fs/cgroup/devices/devices.list"
	out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
	c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
}
func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
	testRequires(c, NativeExecDriver, NotUserNamespace)
	if _, err := os.Stat("/dev/snd"); err != nil {
		c.Skip("Host does not have /dev/snd")
	}

	out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
	if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "timer") {
		c.Fatalf("expected output /dev/snd/timer, received %s", actual)
	}

	out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
	if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "seq") {
		c.Fatalf("expected output /dev/othersnd/seq, received %s", actual)
	}
}
func (s *DockerSuite) TestPsListContainersSize(c *check.C) {
	// TODO Windows: Figure out why TestPsListContainers* are flakey
	if daemonPlatform == "windows" {
		c.Skip("Flaky on windowsTP4")
	}

	// Problematic on Windows as it doesn't report the size correctly @swernli
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "busybox")

	baseOut, _ := dockerCmd(c, "ps", "-s", "-n=1")
	baseLines := strings.Split(strings.Trim(baseOut, "\n "), "\n")
	baseSizeIndex := strings.Index(baseLines[0], "SIZE")
	baseFoundsize := baseLines[1][baseSizeIndex:]
	baseBytes, err := strconv.Atoi(strings.Split(baseFoundsize, " ")[0])
	c.Assert(err, checker.IsNil)

	name := "test_size"
	dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test")
	id, err := getIDByName(name)
	c.Assert(err, checker.IsNil)

	runCmd := exec.Command(dockerBinary, "ps", "-s", "-n=1")
	var out string

	wait := make(chan struct{})
	go func() {
		out, _, err = runCommandWithOutput(runCmd)
		close(wait)
	}()
	select {
	case <-wait:
	case <-time.After(3 * time.Second):
		c.Fatalf("Calling \"docker ps -s\" timed out!")
	}
	c.Assert(err, checker.IsNil)
	lines := strings.Split(strings.Trim(out, "\n "), "\n")
	c.Assert(lines, checker.HasLen, 2, check.Commentf("Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines)))
	sizeIndex := strings.Index(lines[0], "SIZE")
	idIndex := strings.Index(lines[0], "CONTAINER ID")
	foundID := lines[1][idIndex : idIndex+12]
	c.Assert(foundID, checker.Equals, id[:12], check.Commentf("Expected id %s, got %s", id[:12], foundID))
	expectedSize := fmt.Sprintf("%d B", (2 + baseBytes))
	foundSize := lines[1][sizeIndex:]
	c.Assert(foundSize, checker.Contains, expectedSize, check.Commentf("Expected size %q, got %q", expectedSize, foundSize))
}
Beispiel #27
0
func (s *DockerTrustSuite) TestTrustedPushWithExpiredTimestamp(c *check.C) {
	c.Skip("Currently changes system time, causing instability")
	repoName := fmt.Sprintf("%v/dockercliexpiredtimestamppush/trusted:latest", privateRegistryURL)
	// tag the image and upload it to the private registry
	dockerCmd(c, "tag", "busybox", repoName)

	// Push with default passphrases
	icmd.RunCmd(icmd.Command(dockerBinary, "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)

	// The timestamps expire in two weeks. Lets check three
	threeWeeksLater := time.Now().Add(time.Hour * 24 * 21)

	// Should succeed because the server transparently re-signs one
	testutil.RunAtDifferentDate(threeWeeksLater, func() {
		icmd.RunCmd(icmd.Command(dockerBinary, "push", repoName),
			trustedCmd).Assert(c, SuccessSigningAndPushing)
	})
}
func (s *DockerSuite) TestRunWithCorrectMemorySwapOnLXC(c *check.C) {
	testRequires(c, memoryLimitSupport)
	testRequires(c, swapMemorySupport)
	testRequires(c, SameHostDaemon)

	out, _ := dockerCmd(c, "run", "-d", "-m", "32m", "--memory-swap", "64m", "busybox", "top")
	if _, err := os.Stat("/sys/fs/cgroup/memory/lxc"); err != nil {
		c.Skip("Excecution driver must be LXC for this test")
	}
	id := strings.TrimSpace(out)
	memorySwap, err := ioutil.ReadFile(fmt.Sprintf("/sys/fs/cgroup/memory/lxc/%s/memory.memsw.limit_in_bytes", id))
	c.Assert(err, check.IsNil)
	cgSwap, err := strconv.ParseInt(strings.TrimSpace(string(memorySwap)), 10, 64)
	c.Assert(err, check.IsNil)
	swap, err := units.RAMInBytes("64m")
	c.Assert(err, check.IsNil)
	c.Assert(cgSwap, check.Equals, swap)
}
func getExternalAddress(c *check.C) net.IP {
	iface, err := net.InterfaceByName("eth0")
	if err != nil {
		c.Skip(fmt.Sprintf("Test not running with `make test`. Interface eth0 not found: %v", err))
	}

	ifaceAddrs, err := iface.Addrs()
	if err != nil || len(ifaceAddrs) == 0 {
		c.Fatalf("Error retrieving addresses for eth0: %v (%d addresses)", err, len(ifaceAddrs))
	}

	ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String())
	if err != nil {
		c.Fatalf("Error retrieving the up for eth0: %s", err)
	}

	return ifaceIP
}
func (s *DockerSuite) TestLinksEtcHostsContentMatch(c *check.C) {
	testRequires(c, SameHostDaemon)

	runCmd := exec.Command(dockerBinary, "run", "--net=host", "busybox", "cat", "/etc/hosts")
	out, _, _, err := runCommandWithStdoutStderr(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	hosts, err := ioutil.ReadFile("/etc/hosts")
	if os.IsNotExist(err) {
		c.Skip("/etc/hosts does not exist, skip this test")
	}

	if out != string(hosts) {
		c.Errorf("container")
	}

}