// #5979
func (s *DockerSuite) TestEventsRedirectStdout(c *check.C) {
	since := daemonTime(c).Unix()
	dockerCmd(c, "run", "busybox", "true")

	file, err := ioutil.TempFile("", "")
	c.Assert(err, checker.IsNil, check.Commentf("could not create temp file"))
	defer os.Remove(file.Name())

	command := fmt.Sprintf("%s events --since=%d --until=%d > %s", dockerBinary, since, daemonTime(c).Unix(), file.Name())
	_, tty, err := pty.Open()
	c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
	cmd := exec.Command("sh", "-c", command)
	cmd.Stdin = tty
	cmd.Stdout = tty
	cmd.Stderr = tty
	c.Assert(cmd.Run(), checker.IsNil, check.Commentf("run err for command %q", command))

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		for _, ch := range scanner.Text() {
			c.Assert(unicode.IsControl(ch), checker.False, check.Commentf("found control character %v", []byte(string(ch))))
		}
	}
	c.Assert(scanner.Err(), checker.IsNil, check.Commentf("Scan err for command %q", command))

}
// Ensure an error occurs when you have a container read-only rootfs but you
// extract an archive to a symlink in a writable volume which points to a
// directory outside of the volume.
func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs(c *check.C) {
	// Requires local volume mount bind.
	// --read-only + userns has remount issues
	testRequires(c, SameHostDaemon, NotUserNamespace)

	testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-")
	defer os.RemoveAll(testVol)

	makeTestContentInDir(c, testVol)

	cID := makeTestContainer(c, testContainerOptions{
		readOnly: true,
		volumes:  defaultVolumes(testVol), // Our bind mount is at /vol2
	})
	defer deleteContainer(cID)

	// Attempt to extract to a symlink in the volume which points to a
	// directory outside the volume. This should cause an error because the
	// rootfs is read-only.
	query := make(url.Values, 1)
	query.Set("path", "/vol2/symlinkToAbsDir")
	urlPath := fmt.Sprintf("/v1.20/containers/%s/archive?%s", cID, query.Encode())

	statusCode, body, err := sockRequest("PUT", urlPath, nil)
	c.Assert(err, check.IsNil)

	if !isCpCannotCopyReadOnly(fmt.Errorf(string(body))) {
		c.Fatalf("expected ErrContainerRootfsReadonly error, but got %d: %s", statusCode, string(body))
	}
}
// #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume
func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox")

	fooDir, err := inspectMountSourceField("one", "/foo")
	if err != nil {
		c.Fatal(err)
	}

	dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox")

	bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
	status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusNoContent)

	fooDir2, err := inspectMountSourceField("two", "/foo")
	if err != nil {
		c.Fatal(err)
	}

	if fooDir2 != fooDir {
		c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
	}
}
func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
	testRequires(c, blkioWeight)
	out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
	c.Assert(err, check.NotNil, check.Commentf(out))
	expected := "Range of blkio weight is from 10 to 1000"
	c.Assert(out, checker.Contains, expected)
}
示例#5
0
func (s *DockerSuite) TestEventsFilterImageName(c *check.C) {
	since := daemonUnixTime(c)

	out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true")
	container1 := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true")
	container2 := strings.TrimSpace(out)

	name := "busybox"
	out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name))
	events := strings.Split(out, "\n")
	events = events[:len(events)-1]
	c.Assert(events, checker.Not(checker.HasLen), 0) //Expected events but found none for the image busybox:latest
	count1 := 0
	count2 := 0

	for _, e := range events {
		if strings.Contains(e, container1) {
			count1++
		} else if strings.Contains(e, container2) {
			count2++
		}
	}
	c.Assert(count1, checker.Not(checker.Equals), 0, check.Commentf("Expected event from container but got %d from %s", count1, container1))
	c.Assert(count2, checker.Not(checker.Equals), 0, check.Commentf("Expected event from container but got %d from %s", count2, container2))

}
func (s *DockerSuite) TestVolumeEvents(c *check.C) {
	testRequires(c, DaemonIsLinux)

	since := daemonTime(c).Unix()

	// Observe create/mount volume actions
	dockerCmd(c, "volume", "create", "--name", "test-event-volume-local")
	dockerCmd(c, "run", "--name", "test-volume-container", "--volume", "test-event-volume-local:/foo", "-d", "busybox", "true")
	waitRun("test-volume-container")

	// Observe unmount/destroy volume actions
	dockerCmd(c, "rm", "-f", "test-volume-container")
	dockerCmd(c, "volume", "rm", "test-event-volume-local")

	out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	events := strings.Split(strings.TrimSpace(out), "\n")
	c.Assert(len(events), checker.GreaterThan, 4)

	volumeEvents := eventActionsByIDAndType(c, events, "test-event-volume-local", "volume")
	c.Assert(volumeEvents, checker.HasLen, 4)
	c.Assert(volumeEvents[0], checker.Equals, "create")
	c.Assert(volumeEvents[1], checker.Equals, "mount")
	c.Assert(volumeEvents[2], checker.Equals, "unmount")
	c.Assert(volumeEvents[3], checker.Equals, "destroy")
}
func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
	name := "exportcontainer"
	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "touch", "/test")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatalf("Error on container creation: %v, output: %q", err, out)
	}

	status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
	c.Assert(status, check.Equals, http.StatusOK)
	c.Assert(err, check.IsNil)

	found := false
	for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
		h, err := tarReader.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			c.Fatal(err)
		}
		if h.Name == "test" {
			found = true
			break
		}
	}

	if !found {
		c.Fatalf("The created test file has not been found in the exported image")
	}
}
func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
	testRequires(c, DaemonIsLinux)
	cName := "testapicommit"
	dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")

	name := "TestContainerApiCommit"
	status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusCreated)

	type resp struct {
		ID string
	}
	var img resp
	if err := json.Unmarshal(b, &img); err != nil {
		c.Fatal(err)
	}

	cmd, err := inspectField(img.ID, "Config.Cmd")
	if err != nil {
		c.Fatal(err)
	}
	if cmd != "{[/bin/sh -c touch /test]}" {
		c.Fatalf("got wrong Cmd from commit: %q", cmd)
	}
	// sanity check, make sure the image is what we think it is
	dockerCmd(c, "run", img.ID, "ls", "/test")
}
func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
	testRequires(c, DaemonIsLinux)
	name := "changescontainer"
	dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")

	status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	changes := []struct {
		Kind int
		Path string
	}{}
	if err = json.Unmarshal(body, &changes); err != nil {
		c.Fatalf("unable to unmarshal response body: %v", err)
	}

	// Check the changelog for removal of /etc/passwd
	success := false
	for _, elem := range changes {
		if elem.Path == "/etc/passwd" && elem.Kind == 2 {
			success = true
		}
	}
	if !success {
		c.Fatalf("/etc/passwd has been removed but is not present in the diff")
	}
}
示例#10
0
func (s *DockerSuite) TestEventsOOMDisableFalse(c *check.C) {
	testRequires(c, DaemonIsLinux, oomControl, memoryLimitSupport, NotGCCGO)

	errChan := make(chan error)
	go func() {
		defer close(errChan)
		out, exitCode, _ := dockerCmdWithError("run", "--name", "oomFalse", "-m", "10MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
		if expected := 137; exitCode != expected {
			errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
		}
	}()
	select {
	case err := <-errChan:
		c.Assert(err, checker.IsNil)
	case <-time.After(30 * time.Second):
		c.Fatal("Timeout waiting for container to die on OOM")
	}

	out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", fmt.Sprintf("--until=%d", daemonTime(c).Unix()))
	events := strings.Split(strings.TrimSuffix(out, "\n"), "\n")
	nEvents := len(events)

	c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event
	c.Assert(parseEventAction(c, events[nEvents-5]), checker.Equals, "create")
	c.Assert(parseEventAction(c, events[nEvents-4]), checker.Equals, "attach")
	c.Assert(parseEventAction(c, events[nEvents-3]), checker.Equals, "start")
	c.Assert(parseEventAction(c, events[nEvents-2]), checker.Equals, "oom")
	c.Assert(parseEventAction(c, events[nEvents-1]), checker.Equals, "die")
}
func (s *DockerSuite) TestContainerApiGetExport(c *check.C) {
	testRequires(c, DaemonIsLinux)
	name := "exportcontainer"
	dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")

	status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	found := false
	for tarReader := tar.NewReader(bytes.NewReader(body)); ; {
		h, err := tarReader.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			c.Fatal(err)
		}
		if h.Name == "test" {
			found = true
			break
		}
	}

	if !found {
		c.Fatalf("The created test file has not been found in the exported image")
	}
}
示例#12
0
func (s *DockerSuite) TestExecTTYWithoutStdin(c *check.C) {
	out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox")
	id := strings.TrimSpace(out)
	c.Assert(waitRun(id), checker.IsNil)

	errChan := make(chan error)
	go func() {
		defer close(errChan)

		cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true")
		if _, err := cmd.StdinPipe(); err != nil {
			errChan <- err
			return
		}

		expected := "the input device is not a TTY"
		if runtime.GOOS == "windows" {
			expected += ".  If you are using mintty, try prefixing the command with 'winpty'"
		}
		if out, _, err := runCommandWithOutput(cmd); err == nil {
			errChan <- fmt.Errorf("exec should have failed")
			return
		} else if !strings.Contains(out, expected) {
			errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected)
			return
		}
	}()

	select {
	case err := <-errChan:
		c.Assert(err, check.IsNil)
	case <-time.After(3 * time.Second):
		c.Fatal("exec is running but should have failed")
	}
}
示例#13
0
func (s *DockerSuite) TestExecStopNotHanging(c *check.C) {
	// TODO Windows CI: Requires some extra work. Consider copying the
	// runSleepingContainer helper to have an exec version.
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")

	err := exec.Command(dockerBinary, "exec", "testing", "top").Start()
	c.Assert(err, checker.IsNil)

	type dstop struct {
		out []byte
		err error
	}

	ch := make(chan dstop)
	go func() {
		out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput()
		ch <- dstop{out, err}
		close(ch)
	}()
	select {
	case <-time.After(3 * time.Second):
		c.Fatal("Container stop timed out")
	case s := <-ch:
		c.Assert(s.err, check.IsNil)
	}
}
func (s *DockerSuite) TestRestartPolicyNO(c *check.C) {
	out, _ := dockerCmd(c, "run", "-d", "--restart=no", "busybox", "false")

	id := strings.TrimSpace(string(out))
	name := inspectField(c, id, "HostConfig.RestartPolicy.Name")
	c.Assert(name, checker.Equals, "no")
}
func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) {
	out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
	out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false")

	id1 := strings.TrimSpace(string(out1))
	id2 := strings.TrimSpace(string(out2))
	err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second)
	c.Assert(err, checker.IsNil)

	// TODO: fix racey problem during restart:
	// https://jenkins.dockerproject.org/job/Docker-PRs-Win2Lin/24665/console
	// Error response from daemon: Cannot restart container 6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251: remove /var/run/docker/libcontainerd/6655f620d90b390527db23c0a15b3e46d86a58ecec20a5697ab228d860174251/rootfs: device or resource busy
	if _, _, err := dockerCmdWithError("restart", id1); err != nil {
		// if restart met racey problem, try again
		time.Sleep(500 * time.Millisecond)
		dockerCmd(c, "restart", id1)
	}
	if _, _, err := dockerCmdWithError("restart", id2); err != nil {
		// if restart met racey problem, try again
		time.Sleep(500 * time.Millisecond)
		dockerCmd(c, "restart", id2)
	}

	dockerCmd(c, "stop", id1)
	dockerCmd(c, "stop", id2)
	dockerCmd(c, "start", id1)
	dockerCmd(c, "start", id2)
}
func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) {
	name := "changescontainer"
	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "rm", "/etc/passwd")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatalf("Error on container creation: %v, output: %q", err, out)
	}

	status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil)
	c.Assert(status, check.Equals, http.StatusOK)
	c.Assert(err, check.IsNil)

	changes := []struct {
		Kind int
		Path string
	}{}
	if err = json.Unmarshal(body, &changes); err != nil {
		c.Fatalf("unable to unmarshal response body: %v", err)
	}

	// Check the changelog for removal of /etc/passwd
	success := false
	for _, elem := range changes {
		if elem.Path == "/etc/passwd" && elem.Kind == 2 {
			success = true
		}
	}
	if !success {
		c.Fatalf("/etc/passwd has been removed but is not present in the diff")
	}
}
func (s *DockerSuite) TestContainerApiCreate(c *check.C) {
	config := map[string]interface{}{
		"Image": "busybox",
		"Cmd":   []string{"/bin/sh", "-c", "touch /test && ls /test"},
	}

	status, b, err := sockRequest("POST", "/containers/create", config)
	c.Assert(status, check.Equals, http.StatusCreated)
	c.Assert(err, check.IsNil)

	type createResp struct {
		Id string
	}
	var container createResp
	if err := json.Unmarshal(b, &container); err != nil {
		c.Fatal(err)
	}

	out, err := exec.Command(dockerBinary, "start", "-a", container.Id).CombinedOutput()
	if err != nil {
		c.Fatal(out, err)
	}
	if strings.TrimSpace(string(out)) != "/test" {
		c.Fatalf("expected output `/test`, got %q", out)
	}
}
func (s *DockerSuite) TestContainerApiCommit(c *check.C) {
	cName := "testapicommit"
	out, err := exec.Command(dockerBinary, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test").CombinedOutput()
	if err != nil {
		c.Fatal(err, out)
	}

	name := "TestContainerApiCommit"
	status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil)
	c.Assert(status, check.Equals, http.StatusCreated)
	c.Assert(err, check.IsNil)

	type resp struct {
		Id string
	}
	var img resp
	if err := json.Unmarshal(b, &img); err != nil {
		c.Fatal(err)
	}

	cmd, err := inspectField(img.Id, "Config.Cmd")
	if err != nil {
		c.Fatal(err)
	}
	if cmd != "{[/bin/sh -c touch /test]}" {
		c.Fatalf("got wrong Cmd from commit: %q", cmd)
	}
	// sanity check, make sure the image is what we think it is
	out, err = exec.Command(dockerBinary, "run", img.Id, "ls", "/test").CombinedOutput()
	if err != nil {
		c.Fatalf("error checking committed image: %v - %q", err, string(out))
	}
}
示例#19
0
func (s *DockerSuite) TestApiNetworkGetDefaults(c *check.C) {
	// By default docker daemon creates 3 networks. check if they are present
	defaults := []string{"bridge", "host", "none"}
	for _, nn := range defaults {
		c.Assert(isNetworkAvailable(c, nn), checker.Equals, true)
	}
}
示例#20
0
func (s *DockerSuite) TestEventsCopy(c *check.C) {
	// Build a test image.
	id, err := buildImage("cpimg", `
		  FROM busybox
		  RUN echo HI > /file`, true)
	c.Assert(err, checker.IsNil, check.Commentf("Couldn't create image"))

	// Create an empty test file.
	tempFile, err := ioutil.TempFile("", "test-events-copy-")
	c.Assert(err, checker.IsNil)
	defer os.Remove(tempFile.Name())

	c.Assert(tempFile.Close(), checker.IsNil)

	dockerCmd(c, "create", "--name=cptest", id)

	dockerCmd(c, "cp", "cptest:/file", tempFile.Name())

	until := daemonUnixTime(c)
	out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until)
	c.Assert(out, checker.Contains, "archive-path", check.Commentf("Missing 'archive-path' log event\n"))

	dockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy")

	until = daemonUnixTime(c)
	out, _ = dockerCmd(c, "events", "-f", "container=cptest", "--until="+until)
	c.Assert(out, checker.Contains, "extract-to-dir", check.Commentf("Missing 'extract-to-dir' log event"))
}
示例#21
0
// #25798
func (s *DockerSuite) TestEventsSpecialFiltersWithExecCreate(c *check.C) {
	since := daemonUnixTime(c)
	runSleepingContainer(c, "--name", "test-container", "-d")
	waitRun("test-container")

	dockerCmd(c, "exec", "test-container", "echo", "hello-world")

	out, _ := dockerCmd(
		c,
		"events",
		"--since", since,
		"--until", daemonUnixTime(c),
		"--filter",
		"event='exec_create: echo hello-world'",
	)

	events := strings.Split(strings.TrimSpace(out), "\n")
	c.Assert(len(events), checker.Equals, 1, check.Commentf(out))

	out, _ = dockerCmd(
		c,
		"events",
		"--since", since,
		"--until", daemonUnixTime(c),
		"--filter",
		"event=exec_create",
	)
	c.Assert(len(events), checker.Equals, 1, check.Commentf(out))
}
示例#22
0
func (s *DockerSuite) TestEventsLimit(c *check.C) {
	// Limit to 8 goroutines creating containers in order to prevent timeouts
	// creating so many containers simultaneously on Windows
	sem := make(chan bool, 8)
	numContainers := 17
	errChan := make(chan error, numContainers)

	args := []string{"run", "--rm", "busybox", "true"}
	for i := 0; i < numContainers; i++ {
		sem <- true
		go func() {
			defer func() { <-sem }()
			out, err := exec.Command(dockerBinary, args...).CombinedOutput()
			if err != nil {
				err = fmt.Errorf("%v: %s", err, string(out))
			}
			errChan <- err
		}()
	}

	// Wait for all goroutines to finish
	for i := 0; i < cap(sem); i++ {
		sem <- true
	}
	close(errChan)

	for err := range errChan {
		c.Assert(err, checker.IsNil, check.Commentf("%q failed with error", strings.Join(args, " ")))
	}

	out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c))
	events := strings.Split(out, "\n")
	nEvents := len(events) - 1
	c.Assert(nEvents, checker.Equals, 64, check.Commentf("events should be limited to 64, but received %d", nEvents))
}
func (s *DockerSuite) TestContainerApiGetAll(c *check.C) {
	testRequires(c, DaemonIsLinux)
	startCount, err := getContainerCount()
	if err != nil {
		c.Fatalf("Cannot query container count: %v", err)
	}

	name := "getall"
	dockerCmd(c, "run", "--name", name, "busybox", "true")

	status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	var inspectJSON []struct {
		Names []string
	}
	if err = json.Unmarshal(body, &inspectJSON); err != nil {
		c.Fatalf("unable to unmarshal response body: %v", err)
	}

	if len(inspectJSON) != startCount+1 {
		c.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount)
	}

	if actual := inspectJSON[0].Names[0]; actual != "/"+name {
		c.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual)
	}
}
示例#24
0
func (s *DockerSuite) TestExecTtyWithoutStdin(c *check.C) {
	out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox")
	id := strings.TrimSpace(out)
	if err := waitRun(id); err != nil {
		c.Fatal(err)
	}

	errChan := make(chan error)
	go func() {
		defer close(errChan)

		cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true")
		if _, err := cmd.StdinPipe(); err != nil {
			errChan <- err
			return
		}

		expected := "cannot enable tty mode"
		if out, _, err := runCommandWithOutput(cmd); err == nil {
			errChan <- fmt.Errorf("exec should have failed")
			return
		} else if !strings.Contains(out, expected) {
			errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected)
			return
		}
	}()

	select {
	case err := <-errChan:
		c.Assert(err, check.IsNil)
	case <-time.After(3 * time.Second):
		c.Fatal("exec is running but should have failed")
	}
}
// regression test for empty json field being omitted #13691
func (s *DockerSuite) TestContainerApiGetJSONNoFieldsOmitted(c *check.C) {
	testRequires(c, DaemonIsLinux)
	dockerCmd(c, "run", "busybox", "true")

	status, body, err := sockRequest("GET", "/containers/json?all=1", nil)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusOK)

	// empty Labels field triggered this bug, make sense to check for everything
	// cause even Ports for instance can trigger this bug
	// better safe than sorry..
	fields := []string{
		"Id",
		"Names",
		"Image",
		"Command",
		"Created",
		"Ports",
		"Labels",
		"Status",
	}

	// decoding into types.Container do not work since it eventually unmarshal
	// and empty field to an empty go map, so we just check for a string
	for _, f := range fields {
		if !strings.Contains(string(body), f) {
			c.Fatalf("Field %s is missing and it shouldn't", f)
		}
	}
}
示例#26
0
func (s *DockerSuite) TestExecStopNotHanging(c *check.C) {
	dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top")

	if err := exec.Command(dockerBinary, "exec", "testing", "top").Start(); err != nil {
		c.Fatal(err)
	}

	type dstop struct {
		out []byte
		err error
	}

	ch := make(chan dstop)
	go func() {
		out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput()
		ch <- dstop{out, err}
		close(ch)
	}()
	select {
	case <-time.After(3 * time.Second):
		c.Fatal("Container stop timed out")
	case s := <-ch:
		c.Assert(s.err, check.IsNil)
	}
}
func (s *DockerSuite) TestContainerApiBadPort(c *check.C) {
	testRequires(c, DaemonIsLinux)
	config := map[string]interface{}{
		"Image": "busybox",
		"Cmd":   []string{"/bin/sh", "-c", "echo test"},
		"PortBindings": map[string]interface{}{
			"8080/tcp": []map[string]interface{}{
				{
					"HostIP":   "",
					"HostPort": "aa80",
				},
			},
		},
	}

	jsonData := bytes.NewBuffer(nil)
	json.NewEncoder(jsonData).Encode(config)

	status, b, err := sockRequest("POST", "/containers/create", config)
	c.Assert(err, check.IsNil)
	c.Assert(status, check.Equals, http.StatusInternalServerError)

	if strings.TrimSpace(string(b)) != `Invalid port specification: "aa80"` {
		c.Fatalf("Incorrect error msg: %s", string(b))
	}
}
示例#28
0
// #18453
func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) {
	testRequires(c, DaemonIsLinux)
	var (
		out string
		ch  chan struct{}
	)
	ch = make(chan struct{})

	// calculate the time it takes to create and start a container and sleep 2 seconds
	// this is to make sure the docker event will recevie the event of container
	since := daemonTime(c).Unix()
	id, _ := dockerCmd(c, "run", "-d", "busybox", "top")
	cID := strings.TrimSpace(id)
	waitRun(cID)
	time.Sleep(2 * time.Second)
	duration := daemonTime(c).Unix() - since

	go func() {
		out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix()+2*duration))
		close(ch)
	}()
	// Sleep 2 second to wait docker event to start
	time.Sleep(2 * time.Second)
	id, _ = dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
	cID = strings.TrimSpace(id)
	waitRun(cID)
	<-ch
	c.Assert(out, checker.Contains, cID, check.Commentf("Missing event of container (foo)"))
}
示例#29
0
// make sure the default profile can be successfully parsed (using unshare as it is
// something which we know is blocked in the default profile)
func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
	testRequires(c, SameHostDaemon, seccompEnabled)

	out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
	c.Assert(err, checker.NotNil, check.Commentf(out))
	c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
}
// #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume
func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) {
	out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=one", "busybox"))
	if err != nil {
		c.Fatal(err, out)
	}

	fooDir, err := inspectFieldMap("one", "Volumes", "/foo")
	if err != nil {
		c.Fatal(err)
	}

	out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "create", "-v", "/foo", "--name=two", "busybox"))
	if err != nil {
		c.Fatal(err, out)
	}

	bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}}
	status, _, err := sockRequest("POST", "/containers/two/start", bindSpec)
	c.Assert(status, check.Equals, http.StatusNoContent)
	c.Assert(err, check.IsNil)

	fooDir2, err := inspectFieldMap("two", "Volumes", "/foo")
	if err != nil {
		c.Fatal(err)
	}

	if fooDir2 != fooDir {
		c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2)
	}
}