Skip to content

Commit e01ce69

Browse files
committed
cli/command/container: collect: handle context-cancellation
construct the decoder inside the go-routine, including closing the body, and add handling for context-cancellation. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 292001a commit e01ce69

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

cli/command/container/stats_helpers.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ func (s *stats) isKnownContainer(cid string) (int, bool) {
4949
return -1, false
5050
}
5151

52-
func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, streamStats bool, waitFirst *sync.WaitGroup) {
52+
func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, streamStats bool, waitFirst *sync.WaitGroup) { //nolint:gocyclo
5353
var (
5454
getFirst bool
5555
previousCPU uint64
@@ -70,11 +70,14 @@ func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, strea
7070
s.SetError(err)
7171
return
7272
}
73-
defer response.Body.Close()
7473

75-
dec := json.NewDecoder(response.Body)
7674
go func() {
75+
defer response.Body.Close()
76+
dec := json.NewDecoder(response.Body)
7777
for {
78+
if ctx.Err() != nil {
79+
return
80+
}
7881
var (
7982
v *container.StatsResponse
8083
memPercent, cpuPercent float64
@@ -141,8 +144,8 @@ func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, strea
141144
}
142145
case err := <-u:
143146
s.SetError(err)
144-
if err == io.EOF {
145-
break
147+
if errors.Is(err, io.EOF) {
148+
return
146149
}
147150
if err != nil {
148151
continue
@@ -152,6 +155,9 @@ func collect(ctx context.Context, s *Stats, cli client.ContainerAPIClient, strea
152155
getFirst = true
153156
waitFirst.Done()
154157
}
158+
case <-ctx.Done():
159+
s.SetError(ctx.Err())
160+
return
155161
}
156162
if !streamStats {
157163
return

0 commit comments

Comments
 (0)