Skip to content

Commit

Permalink
session: fix run and close synchronization
Browse files Browse the repository at this point in the history
Signed-off-by: Tonis Tiigi <tonistiigi@gmail.com>
(cherry picked from commit 64580e7)
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
  • Loading branch information
tonistiigi authored and thaJeztah committed May 19, 2023
1 parent 2951a28 commit b11cd08
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions session/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"net"
"strings"
"sync"

grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/moby/buildkit/identity"
Expand Down Expand Up @@ -36,14 +37,16 @@ type Attachable interface {

// Session is a long running connection between client and a daemon
type Session struct {
id string
name string
sharedKey string
ctx context.Context
cancelCtx func()
done chan struct{}
grpcServer *grpc.Server
conn net.Conn
mu sync.Mutex // synchronizes conn run and close
id string
name string
sharedKey string
ctx context.Context
cancelCtx func()
done chan struct{}
grpcServer *grpc.Server
conn net.Conn
closeCalled bool
}

// NewSession returns a new long running session
Expand Down Expand Up @@ -99,6 +102,11 @@ func (s *Session) ID() string {

// Run activates the session
func (s *Session) Run(ctx context.Context, dialer Dialer) error {
s.mu.Lock()
if s.closeCalled {
s.mu.Unlock()
return nil
}
ctx, cancel := context.WithCancel(ctx)
s.cancelCtx = cancel
s.done = make(chan struct{})
Expand All @@ -118,22 +126,27 @@ func (s *Session) Run(ctx context.Context, dialer Dialer) error {
}
conn, err := dialer(ctx, "h2c", meta)
if err != nil {
s.mu.Unlock()
return errors.Wrap(err, "failed to dial gRPC")
}
s.conn = conn
s.mu.Unlock()
serve(ctx, s.grpcServer, conn)
return nil
}

// Close closes the session
func (s *Session) Close() error {
s.mu.Lock()
if s.cancelCtx != nil && s.done != nil {
if s.conn != nil {
s.conn.Close()
}
s.grpcServer.Stop()
<-s.done
}
s.closeCalled = true
s.mu.Unlock()
return nil
}

Expand Down

0 comments on commit b11cd08

Please sign in to comment.