Skip to content

Commit

Permalink
Always close the build context
Browse files Browse the repository at this point in the history
This ensures all resources are released properly.
  • Loading branch information
ash2k committed Jul 5, 2024
1 parent 2440699 commit 13d0b22
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
14 changes: 8 additions & 6 deletions container.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ func (c *ContainerRequest) Validate() error {
}

// GetContext retrieve the build context for the request
// Must be closed when no longer needed.
func (c *ContainerRequest) GetContext() (io.Reader, error) {
var includes []string = []string{"."}

Expand Down Expand Up @@ -356,12 +357,6 @@ func (c *ContainerRequest) BuildOptions() (types.ImageBuildOptions, error) {
buildOptions.BuildArgs = c.GetBuildArgs()
buildOptions.Dockerfile = c.GetDockerfile()

buildContext, err := c.GetContext()
if err != nil {
return buildOptions, err
}
buildOptions.Context = buildContext

// Make sure the auth configs from the Dockerfile are set right after the user-defined build options.
authsFromDockerfile := getAuthConfigsFromDockerfile(c)

Expand Down Expand Up @@ -400,6 +395,13 @@ func (c *ContainerRequest) BuildOptions() (types.ImageBuildOptions, error) {
buildOptions.Labels = core.DefaultLabels(core.SessionID())
}

// Do this as late as possible to ensure we don't leak the context on error/panic.
buildContext, err := c.GetContext()
if err != nil {
return buildOptions, err
}
buildOptions.Context = buildContext

return buildOptions, nil
}

Expand Down
8 changes: 8 additions & 0 deletions docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,7 @@ func (p *DockerProvider) BuildImage(ctx context.Context, img ImageBuildInfo) (st
if err != nil {
return types.ImageBuildResponse{}, backoff.Permanent(err)
}
defer tryClose(buildOptions.Context) // release resources in any case

resp, err := p.client.ImageBuild(ctx, buildOptions.Context, buildOptions)
if err != nil {
Expand Down Expand Up @@ -1662,3 +1663,10 @@ func isPermanentClientError(err error) bool {
}
return false
}

func tryClose(r io.Reader) {
rc, ok := r.(io.Closer)
if ok {
_ = rc.Close()
}
}

0 comments on commit 13d0b22

Please sign in to comment.