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: protect against race condition on shutdown in muxer #712

Merged
merged 1 commit into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 13 additions & 1 deletion muxer/muxer.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ type Muxer struct {
startChan chan bool
doneChan chan bool
waitGroup sync.WaitGroup
waitGroupMutex sync.Mutex
protocolSenders map[uint16]map[ProtocolRole]chan *Segment
protocolReceivers map[uint16]map[ProtocolRole]chan *Segment
protocolReceiversMutex sync.Mutex
Expand Down Expand Up @@ -89,7 +90,9 @@ func New(conn net.Conn) *Muxer {
// We must do this to break out of pending Read() calls to shut down cleanly
_ = m.conn.Close()
// Wait for other goroutines to shutdown
m.waitGroupMutex.Lock()
m.waitGroup.Wait()
m.waitGroupMutex.Unlock()
// Close ErrorChan to signify to consumer that we're shutting down
close(m.errorChan)
}()
Expand Down Expand Up @@ -136,11 +139,20 @@ func (m *Muxer) sendError(err error) {
}

// RegisterProtocol registers the provided protocol ID with the muxer. It returns a channel for sending,
// a channel for receiving, and a channel to know when the muxer is shutting down
// a channel for receiving, and a channel to know when the muxer is shutting down. If the muxer is shutting
// down, this function will return nil values.
func (m *Muxer) RegisterProtocol(
protocolId uint16,
protocolRole ProtocolRole,
) (chan *Segment, chan *Segment, chan bool) {
m.waitGroupMutex.Lock()
defer m.waitGroupMutex.Unlock()
// Check for shutdown
select {
case <-m.doneChan:
return nil, nil, nil
default:
}
// Generate channels
senderChan := make(chan *Segment, 10)
receiverChan := make(chan *Segment, 10)
Expand Down
4 changes: 4 additions & 0 deletions protocol/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ func (p *Protocol) Start() {
p.config.ProtocolId,
muxerProtocolRole,
)
if p.muxerDoneChan == nil {
p.SendError(fmt.Errorf("could not register protocol with muxer"))
return
}

// Create channels
p.sendQueueChan = make(chan Message, 50)
Expand Down