Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3a48e40

Browse files
authored
fix: Race when shutting down and opening WebSockets (#576)
Adding to a WaitGroup while calling wait is a race condition. Surrounding this in a mutex should solve the problem. Since context is used for cancellation on all sockets, cleanup should occur properly. See: https://github.com/coder/coder/runs/5701221057?check_suite_focus=true#step:10:98
1 parent 4448ba2 commit 3a48e40

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

coderd/coderd.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -176,13 +176,18 @@ func New(options *Options) (http.Handler, func()) {
176176
})
177177
})
178178
r.NotFound(site.DefaultHandler().ServeHTTP)
179-
return r, api.websocketWaitGroup.Wait
179+
return r, func() {
180+
api.websocketWaitMutex.Lock()
181+
api.websocketWaitGroup.Wait()
182+
api.websocketWaitMutex.Unlock()
183+
}
180184
}
181185

182186
// API contains all route handlers. Only HTTP handlers should
183187
// be added to this struct for code clarity.
184188
type api struct {
185189
*Options
186190

191+
websocketWaitMutex sync.Mutex
187192
websocketWaitGroup sync.WaitGroup
188193
}

coderd/provisionerdaemons.go

+2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@ import (
3333

3434
// Serves the provisioner daemon protobuf API over a WebSocket.
3535
func (api *api) provisionerDaemonsListen(rw http.ResponseWriter, r *http.Request) {
36+
api.websocketWaitMutex.Lock()
3637
api.websocketWaitGroup.Add(1)
38+
api.websocketWaitMutex.Unlock()
3739
defer api.websocketWaitGroup.Done()
3840

3941
conn, err := websocket.Accept(rw, r, &websocket.AcceptOptions{

coderd/workspaceresources.go

+4
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ func (api *api) workspaceResource(rw http.ResponseWriter, r *http.Request) {
6464
}
6565

6666
func (api *api) workspaceResourceDial(rw http.ResponseWriter, r *http.Request) {
67+
api.websocketWaitMutex.Lock()
6768
api.websocketWaitGroup.Add(1)
69+
api.websocketWaitMutex.Unlock()
6870
defer api.websocketWaitGroup.Done()
6971

7072
resource := httpmw.WorkspaceResourceParam(r)
@@ -112,7 +114,9 @@ func (api *api) workspaceResourceDial(rw http.ResponseWriter, r *http.Request) {
112114
}
113115

114116
func (api *api) workspaceAgentListen(rw http.ResponseWriter, r *http.Request) {
117+
api.websocketWaitMutex.Lock()
115118
api.websocketWaitGroup.Add(1)
119+
api.websocketWaitMutex.Unlock()
116120
defer api.websocketWaitGroup.Done()
117121

118122
agent := httpmw.WorkspaceAgent(r)

0 commit comments

Comments
 (0)