Skip to content

Commit 083b53c

Browse files
authored
Merge commit from fork
[Carry #1] fix goroutine leak of container Attach
2 parents 3eea45b + a0d0f0e commit 083b53c

2 files changed

Lines changed: 12 additions & 4 deletions

File tree

internal/cri/io/container_io.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package io
1818

1919
import (
20+
"context"
2021
"errors"
2122
"fmt"
2223
"io"
@@ -160,7 +161,7 @@ func (c *ContainerIO) Pipe() {
160161

161162
// Attach attaches container stdio.
162163
// TODO(random-liu): Use pools.Copy in docker to reduce memory usage?
163-
func (c *ContainerIO) Attach(opts AttachOptions) {
164+
func (c *ContainerIO) Attach(ctx context.Context, opts AttachOptions) {
164165
var wg sync.WaitGroup
165166
key := util.GenerateID()
166167
stdinKey := streamKey(c.id, "attach-"+key, Stdin)
@@ -201,8 +202,15 @@ func (c *ContainerIO) Attach(opts AttachOptions) {
201202
}
202203

203204
attachStream := func(key string, close <-chan struct{}) {
204-
<-close
205-
log.L.Infof("Attach stream %q closed", key)
205+
select {
206+
case <-close:
207+
log.L.Infof("Attach stream %q closed", key)
208+
case <-ctx.Done():
209+
log.L.Infof("Attach client of %q cancelled", key)
210+
// Avoid writeGroup heap up
211+
c.stdoutGroup.Remove(key)
212+
c.stderrGroup.Remove(key)
213+
}
206214
// Make sure stdin gets closed.
207215
if stdinStreamRC != nil {
208216
stdinStreamRC.Close()

internal/cri/server/container_attach.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,6 @@ func (c *criService) attachContainer(ctx context.Context, id string, stdin io.Re
8282
},
8383
}
8484
// TODO(random-liu): Figure out whether we need to support historical output.
85-
cntr.IO.Attach(opts)
85+
cntr.IO.Attach(ctx, opts)
8686
return nil
8787
}

0 commit comments

Comments
 (0)