Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
240 changes: 129 additions & 111 deletions pkg/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"path"
"path/filepath"
"strings"
"sync"
"time"

docker "github.com/fsouza/go-dockerclient"
Expand Down Expand Up @@ -83,7 +82,7 @@ type Client interface {
InspectImage(name string) (*docker.Image, error)
PullImage(opts docker.PullImageOptions, auth docker.AuthConfiguration) error
CreateContainer(opts docker.CreateContainerOptions) (*docker.Container, error)
AttachToContainer(opts docker.AttachToContainerOptions) error
AttachToContainerNonBlocking(opts docker.AttachToContainerOptions) (docker.CloseWaiter, error)
StartContainer(id string, hostConfig *docker.HostConfig) error
WaitContainer(id string) (int, error)
UploadToContainer(id string, opts docker.UploadToContainerOptions) error
Expand Down Expand Up @@ -132,6 +131,66 @@ type RunContainerOptions struct {
CapDrop []string
}

// asDockerConfig converts a RunContainerOptions into a Config understood by the
// go-dockerclient library.
func (rco RunContainerOptions) asDockerConfig() docker.Config {
return docker.Config{
Image: getImageName(rco.Image),
User: rco.User,
Env: rco.Env,
OpenStdin: rco.Stdin != nil,
StdinOnce: rco.Stdin != nil,
AttachStdout: rco.Stdout != nil,
}
}

// asDockerHostConfig converts a RunContainerOptions into a HostConfig
// understood by the go-dockerclient library.
func (rco RunContainerOptions) asDockerHostConfig() docker.HostConfig {
hostConfig := docker.HostConfig{
CapDrop: rco.CapDrop,
PublishAllPorts: rco.TargetImage,
NetworkMode: rco.NetworkMode,
}
if rco.CGroupLimits != nil {
hostConfig.Memory = rco.CGroupLimits.MemoryLimitBytes
hostConfig.MemorySwap = rco.CGroupLimits.MemorySwap
hostConfig.CPUShares = rco.CGroupLimits.CPUShares
hostConfig.CPUQuota = rco.CGroupLimits.CPUQuota
hostConfig.CPUPeriod = rco.CGroupLimits.CPUPeriod
}
return hostConfig
}

// asDockerCreateContainerOptions converts a RunContainerOptions into a
// CreateContainerOptions understood by the go-dockerclient library.
func (rco RunContainerOptions) asDockerCreateContainerOptions() docker.CreateContainerOptions {
config := rco.asDockerConfig()
hostConfig := rco.asDockerHostConfig()
return docker.CreateContainerOptions{
Name: "",
Config: &config,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not return the pointer from the function? then you don't need these extra vars?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because it's invalid Go code to do what you're saying :P

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is invalid about?

func (rco RunContainerOptions) asDockerConfig() *docker.Config {}

Then you can just do:

Config:  rco.asDockerConfig(),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aha, I thought you meant

{
     Config:     &rco.asDockerConfig(),
     // ...
}

😃

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mfojtik we could do what you propose for asDockerConfig and asDockerHostConfig, but then for asDockerCreateContainerOptions and asDockerAttachToContainerOptions we don't want them to return pointers (for similar reasons in terms of "convenience of use").

That would lead to similar methods some returning pointers, some not.

WDYT of that situation?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(and add it to the list of "poor decisions golang has made")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(and add it to the list of "poor decisions golang has made")

Just for my own curiosity (and for compiling the list 😄 )...
What's the particular poor decision here? How would it be in an "ideal" language?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

func foo() obj {
return obj{}
}

var a *obj
a=&foo()

Basically all i'm asking for (in this case) is syntactic sugar that keeps me from having to declare the temporary variable.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see... on the curiosity side, do you guys know if is it possible to do that in C++ or Java?

That would be the & operator taking the address of the return value of a function call...
Possibly it would be written as &(foo()) so that there's no ambiguity with (&foo)()?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, the goals for me is to keep the amount of temporary vars low (with exception of making the code more readable) and avoid if as much as possible :-)

in this case that function servers as generator for the Config field which require *docker.Config, so having that function return the pointer makes more sense to me ;-)

however, I will still be ok with what you have here today, it just seems odd to always create temp variable to use it :)

HostConfig: &hostConfig,
}
}

// asDockerAttachToContainerOptions converts a RunContainerOptions into a
// AttachToContainerOptions understood by the go-dockerclient library.
func (rco RunContainerOptions) asDockerAttachToContainerOptions() docker.AttachToContainerOptions {
return docker.AttachToContainerOptions{
InputStream: rco.Stdin,
OutputStream: rco.Stdout,
ErrorStream: rco.Stderr,

Stdin: rco.Stdin != nil,
Stdout: rco.Stdout != nil,
Stderr: rco.Stderr != nil,

Logs: rco.Stdout != nil,
Stream: rco.Stdout != nil,
}
}

// CommitContainerOptions are options passed in to the CommitContainer method
type CommitContainerOptions struct {
ContainerID string
Expand Down Expand Up @@ -441,10 +500,9 @@ func getDestination(image *docker.Image) string {
}

// this funtion simply abstracts out the tar related processing that was originally inline in RunContainer()
func runContainerTar(opts RunContainerOptions, config docker.Config, imageMetadata *docker.Image) (docker.Config, string) {
tarDestination := ""
func runContainerTar(opts RunContainerOptions, imageMetadata *docker.Image) (cmd []string, tarDestination string) {
if opts.TargetImage {
return config, tarDestination
return
}

// base directory for all STI commands
Expand Down Expand Up @@ -474,7 +532,7 @@ func runContainerTar(opts RunContainerOptions, config docker.Config, imageMetada

// NOTE: We use path.Join instead of filepath.Join to avoid converting the
// path to UNC (Windows) format as we always run this inside container.
cmd := []string{path.Join(commandBaseDir, string(opts.Command))}
cmd = []string{path.Join(commandBaseDir, string(opts.Command))}
// when calling assemble script with Stdin parameter set (the tar file)
// we need to first untar the whole archive and only then call the assemble script
if opts.Stdin != nil && (opts.Command == api.Assemble || opts.Command == api.Usage) {
Expand All @@ -483,9 +541,8 @@ func runContainerTar(opts RunContainerOptions, config docker.Config, imageMetada
cmd = []string{"/bin/sh", "-c", opts.CommandOverrides(strings.Join(cmd[2:], " "))}
}
}
glog.V(5).Infof("Running %q command in container ...", strings.Join(cmd, " "))
config.Cmd = cmd
return config, tarDestination
glog.V(5).Infof("Setting %q command for container ...", strings.Join(cmd, " "))
return cmd, tarDestination
}

// this funtion simply abstracts out the running of the newly produced image when the --run=true option is provided
Expand Down Expand Up @@ -515,61 +572,17 @@ func runContainerDockerRun(container *docker.Container, d *stiDocker, image stri
glog.V(2).Infof("\nReceived signal '%s', stopping services...\n", signal)
}

// this funtion simply abstracts out the first phase of attaching to the container that was originally in line with the RunContainer() method
func runContainerAttach(attached chan struct{}, container *docker.Container, opts RunContainerOptions, d *stiDocker) *sync.WaitGroup {
attachOpts := docker.AttachToContainerOptions{
Container: container.ID,
Success: attached,
Stream: true,
}
if opts.Stdin != nil {
attachOpts.InputStream = opts.Stdin
attachOpts.Stdin = true
}
if opts.Stdout != nil {
attachOpts.OutputStream = opts.Stdout
attachOpts.Stdout = true
}
if opts.Stderr != nil {
attachOpts.ErrorStream = opts.Stderr
attachOpts.Stderr = true
}

wg := sync.WaitGroup{}
go func() {
wg.Add(1)
defer wg.Done()
if err := d.client.AttachToContainer(attachOpts); err != nil {
glog.Errorf("Unable to attach container with %v", attachOpts)
}
}()
return &wg
}

// this funtion simply abstracts out the waiting on the container hosting the builder function that was originally in line with the RunContainer() method
func runContainerWait(wg *sync.WaitGroup, d *stiDocker, container *docker.Container) error {
glog.V(2).Infof("Waiting for container")
exitCode, err := d.client.WaitContainer(container.ID)
glog.V(2).Infof("Container wait returns with %d and %v\n", exitCode, err)
// RunContainer creates and starts a container using the image specified in opts
// with the ability to stream input and/or output.
func (d *stiDocker) RunContainer(opts RunContainerOptions) error {
createOpts := opts.asDockerCreateContainerOptions()

wg.Wait()
if err != nil {
return err
}

glog.V(2).Infof("Container exited")
if exitCode != 0 {
return errors.NewContainerError(container.Name, exitCode, "")
}
return nil
}

// RunContainer creates and starts a container using the image specified in the options with the ability
// to stream input or output
func (d *stiDocker) RunContainer(opts RunContainerOptions) (err error) {
// get info about the specified image
image := getImageName(opts.Image)
var imageMetadata *docker.Image
image := createOpts.Config.Image
var (
imageMetadata *docker.Image
err error
)
if opts.PullImage {
imageMetadata, err = d.CheckAndPullImage(image)
} else {
Expand All @@ -580,92 +593,97 @@ func (d *stiDocker) RunContainer(opts RunContainerOptions) (err error) {
return err
}

config := docker.Config{
Image: image,
User: opts.User,
}

config, tarDestination := runContainerTar(opts, config, imageMetadata)

if opts.Env != nil {
config.Env = opts.Env
}
if opts.Stdin != nil {
config.OpenStdin = true
config.StdinOnce = true
}
if opts.Stdout != nil {
config.AttachStdout = true
}

ccopts := docker.CreateContainerOptions{Name: "", Config: &config}
ccopts.HostConfig = &docker.HostConfig{}
if opts.TargetImage {
ccopts.HostConfig.PublishAllPorts = true
ccopts.HostConfig.NetworkMode = opts.NetworkMode
} else if opts.NetworkMode != "" {
ccopts.HostConfig.NetworkMode = opts.NetworkMode
}

if opts.CGroupLimits != nil {
ccopts.HostConfig.Memory = opts.CGroupLimits.MemoryLimitBytes
ccopts.HostConfig.MemorySwap = opts.CGroupLimits.MemorySwap
ccopts.HostConfig.CPUShares = opts.CGroupLimits.CPUShares
ccopts.HostConfig.CPUQuota = opts.CGroupLimits.CPUQuota
ccopts.HostConfig.CPUPeriod = opts.CGroupLimits.CPUPeriod
}
ccopts.HostConfig.CapDrop = opts.CapDrop
glog.V(2).Infof("Creating container %s using config: %+v, hostconfig: %+v", ccopts.Name, ccopts.Config, ccopts.HostConfig)
cmd, tarDestination := runContainerTar(opts, imageMetadata)
createOpts.Config.Cmd = cmd

// Create a new container.
glog.V(2).Infof("Creating container with options {Name:%q Config:%+v HostConfig:%+v} ...", createOpts.Name, createOpts.Config, createOpts.HostConfig)
var container *docker.Container
if err := util.TimeoutAfter(DefaultDockerTimeout, func() error {
var createErr error
container, createErr = d.client.CreateContainer(ccopts)
container, createErr = d.client.CreateContainer(createOpts)
return createErr
}); err != nil {
return err
}

defer d.RemoveContainer(container.ID)
containerName := containerNameOrID(container)

glog.V(2).Infof("Attaching to container")
// creating / piping the channels in runContainerAttach lead to unintended hangs
attached := make(chan struct{})
wg := runContainerAttach(attached, container, opts, d)
attached <- <-attached
// Container was created, so we defer its removal.
defer func() {
glog.V(4).Infof("Removing container %q ...", containerName)
if err := d.RemoveContainer(container.ID); err != nil {
glog.Warningf("Failed to remove container %q: %v", containerName, err)
} else {
glog.V(4).Infof("Removed container %q", containerName)
}
}()

glog.V(2).Infof("Starting container")
// Attach to the container.
glog.V(2).Infof("Attaching to container %q ...", containerName)
attachOpts := opts.asDockerAttachToContainerOptions()
attachOpts.Container = container.ID
if _, err = d.client.AttachToContainerNonBlocking(attachOpts); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so is this the meat of the change, that we're calling the non-blocking attach now (and not doing it in a goroutine)? or are the arguments to attach actually different now from what they were?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should not be changes to arguments (attachOpts).
Indeed, using the non-blocking variant.

I expected to be able to use the first return value (now ignored, a CloseWaiter interface type), and call cw.Wait() to wait for it to "detach" when the container terminates.
However that's not the effect it had. Documentation in go-dockerclient is really really lacking... :(

It turns out that just waiting for the container to terminate is fine (line 661 on).

There might be goroutine leaking from go-dockerclient.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There might be goroutine leaking from go-dockerclient.

Or not. Since we always force remove the container, all the resources related to the attach call should be released.
I haven't checked the implementation of client.hijack enough to tell by heart if they have leaks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should not be changes to arguments (attachOpts).

Sorry, that was an incorrect statement. I just remembered that there is a difference, now we're not using the Success field (chan struct{}).

The docs say:

    // If set, after a successful connect, a sentinel will be sent and then the
    // client will block on receive before continuing.
    //
    // It must be an unbuffered channel. Using a buffered channel can lead
    // to unexpected behavior.
    Success chan struct{}

We don't really need to do anything special right after the connection is established. My understanding is that we were just going through unnecessary hops.

We were receiving and sending on that channel without any intermediary steps.

glog.Errorf("Unable to attach to container %q with options %+v: %v", containerName, attachOpts, err)
return err
}

// Start the container.
glog.V(2).Infof("Starting container %q ...", containerName)
if err := util.TimeoutAfter(DefaultDockerTimeout, func() error {
return d.client.StartContainer(container.ID, nil)
}); err != nil {
return err
}

// Run OnStart hook if defined.
if opts.OnStart != nil {
if err = opts.OnStart(container.ID); err != nil {
return err
}
}

// We either block waiting for a user-originated SIGINT, or wait for the
// container to terminate. When TargetImage is true, we're dealing with
// an invocation of `s2i build ... --run` so this will, e.g., run a web
// server and block until the user interrupts it. The other case is seen
// when running the assemble script or other commands that are meant to
// terminate in a finite amount of time.
if opts.TargetImage {

runContainerDockerRun(container, d, image)

} else {
werr := runContainerWait(wg, d, container)
if werr != nil {
return werr
// Return an error if the exit code of the container is
// non-zero.
glog.V(4).Infof("Waiting for container %q to stop ...", containerName)
exitCode, err := d.client.WaitContainer(container.ID)
if err != nil {
return fmt.Errorf("waiting for container %q to stop: %v", containerName, err)
}
if exitCode != 0 {
return errors.NewContainerError(container.Name, exitCode, "")
}
}

// Run PostExec hook if defined.
if opts.PostExec != nil {
glog.V(2).Infof("Invoking postExecution function")
if err = opts.PostExec.PostExecute(container.ID, tarDestination); err != nil {
return err
}
}

return nil
}

// containerName returns the name of a container or its ID if the name is empty.
// Useful for identifying a container in logs.
func containerNameOrID(c *docker.Container) string {
if c.Name != "" {
return c.Name
}
return c.ID
}

// GetImageID retrieves the ID of the image identified by name
func (d *stiDocker) GetImageID(name string) (string, error) {
name = getImageName(name)
Expand Down
16 changes: 0 additions & 16 deletions pkg/docker/docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"os"
"reflect"
"testing"
"time"

"github.com/openshift/source-to-image/pkg/api"
"github.com/openshift/source-to-image/pkg/docker/test"
Expand Down Expand Up @@ -423,7 +422,6 @@ func TestRunContainer(t *testing.T) {
Container: &docker.Container{
ID: "12345-test",
},
AttachToContainerSleep: 200 * time.Millisecond,
}
dh := getDocker(fakeDocker)
err := dh.RunContainer(RunContainerOptions{
Expand Down Expand Up @@ -461,20 +459,6 @@ func TestRunContainer(t *testing.T) {
if fakeDocker.RemoveContainerOpts.ID != "12345-test" {
t.Errorf("%s: RemoveContainer was not called with the expected container ID", desc)
}

// Verify that AttachToContainer was called twice (Stdin/Stdout)
if len(fakeDocker.AttachToContainerOpts) != 1 {
t.Errorf("%s: AttachToContainer was not called the expected number of times.", desc)
}
// Make sure AttachToContainer was not called with both Stdin & Stdout
for _, opt := range fakeDocker.AttachToContainerOpts {
if opt.InputStream == nil || opt.OutputStream == nil {
t.Errorf("%s: AttachToContainer was not called with both Stdin and Stdout: %#v", desc, opt)
}
if !opt.Stdin || !opt.Stdout {
t.Errorf("%s: AttachToContainer was not called with both Stdin and Stdout flags: %#v", desc, opt)
}
}
}
}

Expand Down
8 changes: 1 addition & 7 deletions pkg/docker/fake_docker.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package docker

import (
"sync"

dockerclient "github.com/fsouza/go-dockerclient"
)
import dockerclient "github.com/fsouza/go-dockerclient"

// FakeDocker provides a fake docker interface
type FakeDocker struct {
Expand Down Expand Up @@ -43,8 +39,6 @@ type FakeDocker struct {
IsOnBuildImage string
Labels map[string]string
LabelsError error

mutex sync.Mutex
}

// IsImageInLocalRegistry checks if the image exists in the fake local registry
Expand Down
Loading