Repository navigation
Rework RunContainer implementation #430
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,7 +6,6 @@ import ( | |
| "path" | ||
| "path/filepath" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| docker "github.com/fsouza/go-dockerclient" | ||
|
|
@@ -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 | ||
|
|
@@ -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, | ||
| 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 | ||
|
|
@@ -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 | ||
|
|
@@ -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) { | ||
|
|
@@ -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 | ||
|
|
@@ -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 { | ||
|
|
@@ -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 { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There should not be changes to arguments ( I expected to be able to use the first return value (now ignored, a It turns out that just waiting for the container to terminate is fine (line 661 on). There might be goroutine leaking from go-dockerclient.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Or not. Since we always force remove the container, all the resources related to the attach call should be released.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Sorry, that was an incorrect statement. I just remembered that there is a difference, now we're not using the 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) | ||
|
|
||
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what is invalid about?
Then you can just do:
There was a problem hiding this comment.
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(), // ... }😃
There was a problem hiding this comment.
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
asDockerConfigandasDockerHostConfig, but then forasDockerCreateContainerOptionsandasDockerAttachToContainerOptionswe 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?
There was a problem hiding this comment.
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")
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)()?There was a problem hiding this comment.
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
ifas much as possible :-)in this case that function servers as generator for the
Configfield 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 :)