Skip to content

Commit b5f5740

Browse files
authored
chore: ensure agent conn routine is closed before exit (coder#6900)
This caused a leak in `main`!
1 parent e496bdb commit b5f5740

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

codersdk/agentsdk/agentsdk.go

+20-1
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,15 @@ func (c *Client) Listen(ctx context.Context) (net.Conn, error) {
161161
return nil, codersdk.ReadBodyAsError(res)
162162
}
163163

164+
ctx, cancelFunc := context.WithCancel(ctx)
164165
ctx, wsNetConn := websocketNetConn(ctx, conn, websocket.MessageBinary)
165166

166167
// Ping once every 30 seconds to ensure that the websocket is alive. If we
167168
// don't get a response within 30s we kill the websocket and reconnect.
168169
// See: https://github.com/coder/coder/pull/5824
170+
closed := make(chan struct{})
169171
go func() {
172+
defer close(closed)
170173
tick := 30 * time.Second
171174
ticker := time.NewTicker(tick)
172175
defer ticker.Stop()
@@ -199,7 +202,13 @@ func (c *Client) Listen(ctx context.Context) (net.Conn, error) {
199202
}
200203
}()
201204

202-
return wsNetConn, nil
205+
return &closeNetConn{
206+
Conn: wsNetConn,
207+
closeFunc: func() {
208+
cancelFunc()
209+
<-closed
210+
},
211+
}, nil
203212
}
204213

205214
type PostAppHealthsRequest struct {
@@ -623,3 +632,13 @@ type StartupLogsNotifyMessage struct {
623632
CreatedAfter int64 `json:"created_after"`
624633
EndOfLogs bool `json:"end_of_logs"`
625634
}
635+
636+
type closeNetConn struct {
637+
net.Conn
638+
closeFunc func()
639+
}
640+
641+
func (c *closeNetConn) Close() error {
642+
c.closeFunc()
643+
return c.Conn.Close()
644+
}

0 commit comments

Comments
 (0)