Selaa lähdekoodia

Merge pull request #46268 from thaJeztah/detachcontext

container: internalize InitAttachContext
Sebastiaan van Stijn 1 vuosi sitten
vanhempi
commit
ec7c2b784a
3 muutettua tiedostoa jossa 40 lisäystä ja 23 poistoa
  1. 35 0
      container/attach_context.go
  2. 4 22
      container/container.go
  3. 1 1
      daemon/attach.go

+ 35 - 0
container/attach_context.go

@@ -0,0 +1,35 @@
+package container
+
+import (
+	"context"
+	"sync"
+)
+
+// attachContext is the context used for for attach calls.
+type attachContext struct {
+	mu         sync.Mutex
+	ctx        context.Context
+	cancelFunc context.CancelFunc
+}
+
+// init returns the context for attach calls. It creates a new context
+// if no context is created yet.
+func (ac *attachContext) init() context.Context {
+	ac.mu.Lock()
+	defer ac.mu.Unlock()
+	if ac.ctx == nil {
+		ac.ctx, ac.cancelFunc = context.WithCancel(context.Background())
+	}
+	return ac.ctx
+}
+
+// cancelFunc cancels the attachContext. All attach calls should detach
+// after this call.
+func (ac *attachContext) cancel() {
+	ac.mu.Lock()
+	if ac.ctx != nil {
+		ac.cancelFunc()
+		ac.ctx = nil
+	}
+	ac.mu.Unlock()
+}

+ 4 - 22
container/container.go

@@ -10,7 +10,6 @@ import (
 	"path/filepath"
 	"runtime"
 	"strings"
-	"sync"
 	"syscall"
 	"time"
 
@@ -594,32 +593,15 @@ func (container *Container) ResetRestartManager(resetCount bool) {
 	container.restartManager = nil
 }
 
-type attachContext struct {
-	ctx    context.Context
-	cancel context.CancelFunc
-	mu     sync.Mutex
-}
-
-// InitAttachContext initializes or returns existing context for attach calls to
-// track container liveness.
-func (container *Container) InitAttachContext() context.Context {
-	container.attachContext.mu.Lock()
-	defer container.attachContext.mu.Unlock()
-	if container.attachContext.ctx == nil {
-		container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
-	}
-	return container.attachContext.ctx
+// AttachContext returns the context for attach calls to track container liveness.
+func (container *Container) AttachContext() context.Context {
+	return container.attachContext.init()
 }
 
 // CancelAttachContext cancels attach context. All attach calls should detach
 // after this call.
 func (container *Container) CancelAttachContext() {
-	container.attachContext.mu.Lock()
-	if container.attachContext.ctx != nil {
-		container.attachContext.cancel()
-		container.attachContext.ctx = nil
-	}
-	container.attachContext.mu.Unlock()
+	container.attachContext.cancel()
 }
 
 func (container *Container) startLogging() error {

+ 1 - 1
daemon/attach.go

@@ -175,7 +175,7 @@ func (daemon *Daemon) containerAttach(c *container.Container, cfg *stream.Attach
 		}()
 	}
 
-	ctx := c.InitAttachContext()
+	ctx := c.AttachContext()
 	err := <-c.StreamConfig.CopyStreams(ctx, cfg)
 	if err != nil {
 		var ierr term.EscapeError