예제 #1
0
// StopContainer stops a running container.
func StopContainer(daemon *dockertest.Docker, id string) error {
	client, err := daemon.Client()
	if err != nil {
		return errors.Wrap(err, "unable to create docker client")
	}

	err = client.RemoveContainer(dockerclient.RemoveContainerOptions{
		ID:            id,
		RemoveVolumes: true,
		Force:         true,
	})
	if err != nil {
		return errors.Wrapf(err, "unable to stop container %s", id)
	}
	return nil
}
예제 #2
0
// StartContainer starts a test container and returns its ID.
func StartContainer(daemon *dockertest.Docker, bindings []*beacon.Binding, labels map[string]string) (string, error) {
	client, err := daemon.Client()
	if err != nil {
		return "", errors.Wrap(err, "unable to create docker client")
	}

	exposedPorts := map[dockerclient.Port]struct{}{}
	for _, binding := range bindings {
		port := dockerclient.Port(fmt.Sprintf("%d/%s", binding.ContainerPort, binding.Protocol))
		exposedPorts[port] = struct{}{}
	}

	container, err := client.CreateContainer(dockerclient.CreateContainerOptions{
		Config: &dockerclient.Config{
			Image:        fmt.Sprintf("%s:%s", DOCKER_IMAGE_REPO, DOCKER_IMAGE_TAG),
			Cmd:          []string{"/bin/sh", "-c", "trap exit SIGTERM SIGINT; while true; do sleep 0.1; done"},
			ExposedPorts: exposedPorts,
			Labels:       labels,
		},
	})
	if err != nil {
		return "", errors.Wrap(err, "unable to create docker container")
	}

	portBindings := map[dockerclient.Port][]dockerclient.PortBinding{}
	for _, binding := range bindings {
		port := dockerclient.Port(fmt.Sprintf("%d/%s", binding.ContainerPort, binding.Protocol))
		portBindings[port] = []dockerclient.PortBinding{{
			HostIP:   binding.HostIP,
			HostPort: fmt.Sprintf("%d", binding.HostPort),
		}}
	}

	err = client.StartContainer(container.ID, &dockerclient.HostConfig{
		PortBindings: portBindings,
	})
	if err != nil {
		StopContainer(daemon, container.ID)
		return "", errors.Wrap(err, "unable to start docker container")
	}
	return container.ID, nil
}