Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ShutdownWithContext and ctx.Done() exist race. #1908

Merged
merged 3 commits into from
Dec 8, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: Even if ln.Close() err, the Shutdown process should still proceed.
  • Loading branch information
r27153733 committed Nov 25, 2024
commit 7b151deaa599ec02bf1a775095fac21709e64183
23 changes: 14 additions & 9 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1900,11 +1900,7 @@ func (s *Server) ShutdownWithContext(ctx context.Context) (err error) {
return nil
}

for _, ln := range s.ln {
if err = ln.Close(); err != nil {
return err
}
}
lnerr := s.closeListenersLocked()

if s.done != nil {
close(s.done)
Expand All @@ -1920,6 +1916,9 @@ END:
s.closeIdleConns()

if open := atomic.LoadInt32(&s.open); open == 0 {
err = lnerr
// There may be a pending request to call ctx.Done(). Therefore, we only set it to nil when open == 0.
s.done = nil
break
}
// This is not an optimal solution but using a sync.WaitGroup
Expand All @@ -1934,10 +1933,6 @@ END:
}
}

// There may be a surviving request to call ctx.Done().
if err == nil {
s.done = nil
}
s.ln = nil
return err
}
Expand Down Expand Up @@ -2931,6 +2926,16 @@ func (s *Server) closeIdleConns() {
s.idleConnsMu.Unlock()
}

func (s *Server) closeListenersLocked() error {
var err error
for _, ln := range s.ln {
if cerr := ln.Close(); cerr != nil && err == nil {
err = cerr
}
}
return err
}

// A ConnState represents the state of a client connection to a server.
// It's used by the optional Server.ConnState hook.
type ConnState int
Expand Down