Skip to content

Commit 575a6cd

Browse files
committed
controller: avoid "context canceled" error on cleanup
Signed-off-by: Kohei Tokunaga <ktokunaga.mail@gmail.com>
1 parent ba6e5cd commit 575a6cd

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

build/result.go

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io"
88
"sync"
99
"sync/atomic"
10+
"time"
1011

1112
controllerapi "github.com/docker/buildx/controller/pb"
1213
"github.com/moby/buildkit/client"
@@ -73,9 +74,8 @@ func getResultAt(ctx context.Context, c *client.Client, solveOpt client.SolveOpt
7374
resultCtxCh := make(chan *ResultContext)
7475
errCh := make(chan error)
7576
go func() {
77+
buildDoneCh := make(chan struct{})
7678
_, err := c.Build(context.Background(), solveOpt, "buildx", func(ctx context.Context, c gateway.Client) (*gateway.Result, error) {
77-
ctx, cancel := context.WithCancel(ctx)
78-
defer cancel()
7979
resultCtx := ResultContext{}
8080
res2, err := c.Solve(ctx, gateway.SolveRequest{
8181
Evaluate: true,
@@ -90,18 +90,35 @@ func getResultAt(ctx context.Context, c *client.Client, solveOpt client.SolveOpt
9090
}
9191
}
9292
// Record the client and ctx as well so that containers can be created from the SolveError.
93+
doneCh := make(chan struct{})
9394
resultCtx.res = res2
9495
resultCtx.gwClient = c
9596
resultCtx.gwCtx = ctx
96-
resultCtx.gwDone = cancel
97+
resultCtx.gwDone = func() {
98+
close(doneCh)
99+
// wait for Build() completion(or timeout) to ensure the Build's finalizing and avoiding an error "context canceled"
100+
select {
101+
case <-buildDoneCh:
102+
case <-time.After(5 * time.Second):
103+
}
104+
}
97105
select {
98106
case resultCtxCh <- &resultCtx:
107+
case <-doneCh:
108+
return nil, nil
109+
case <-ctx.Done():
110+
return nil, ctx.Err()
111+
}
112+
113+
// wait for cleanup or cancel
114+
select {
115+
case <-doneCh:
99116
case <-ctx.Done():
100117
return nil, ctx.Err()
101118
}
102-
<-ctx.Done()
103119
return nil, nil
104120
}, ch)
121+
close(buildDoneCh)
105122
if err != nil {
106123
errCh <- err
107124
}

0 commit comments

Comments
 (0)