- Notifications
You must be signed in to change notification settings - Fork920
fix: fix goroutine leak in log streaming over websocket#15709
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
9 changes: 4 additions & 5 deletionscoderd/provisionerjobs.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
24 changes: 7 additions & 17 deletionscoderd/workspaceagents.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -39,6 +39,7 @@ import ( | ||
"github.com/coder/coder/v2/codersdk" | ||
"github.com/coder/coder/v2/codersdk/agentsdk" | ||
"github.com/coder/coder/v2/codersdk/workspacesdk" | ||
"github.com/coder/coder/v2/codersdk/wsjson" | ||
"github.com/coder/coder/v2/tailnet" | ||
"github.com/coder/coder/v2/tailnet/proto" | ||
) | ||
@@ -396,11 +397,9 @@ func (api *API) workspaceAgentLogs(rw http.ResponseWriter, r *http.Request) { | ||
} | ||
go httpapi.Heartbeat(ctx, conn) | ||
encoder:=wsjson.NewEncoder[[]codersdk.WorkspaceAgentLog](conn, websocket.MessageText) | ||
deferencoder.Close(websocket.StatusNormalClosure) | ||
err = encoder.Encode(convertWorkspaceAgentLogs(logs)) | ||
if err != nil { | ||
return | ||
@@ -740,16 +739,8 @@ func (api *API) derpMapUpdates(rw http.ResponseWriter, r *http.Request) { | ||
}) | ||
return | ||
} | ||
encoder := wsjson.NewEncoder[*tailcfg.DERPMap](ws, websocket.MessageBinary) | ||
defer encoder.Close(websocket.StatusGoingAway) | ||
go func(ctx context.Context) { | ||
// TODO(mafredri): Is this too frequent? Use separate ping disconnect timeout? | ||
@@ -767,7 +758,7 @@ func (api *API) derpMapUpdates(rw http.ResponseWriter, r *http.Request) { | ||
err := ws.Ping(ctx) | ||
cancel() | ||
if err != nil { | ||
_ =ws.Close(websocket.StatusGoingAway, "ping failed") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others.Learn more. 👍🏻 | ||
return | ||
} | ||
} | ||
@@ -780,9 +771,8 @@ func (api *API) derpMapUpdates(rw http.ResponseWriter, r *http.Request) { | ||
for { | ||
derpMap := api.DERPMap() | ||
if lastDERPMap == nil || !tailnet.CompareDERPMaps(lastDERPMap, derpMap) { | ||
err :=encoder.Encode(derpMap) | ||
if err != nil { | ||
return | ||
} | ||
lastDERPMap = derpMap | ||
33 changes: 3 additions & 30 deletionscodersdk/provisionerdaemons.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
29 changes: 3 additions & 26 deletionscodersdk/workspaceagents.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
75 changes: 75 additions & 0 deletionscodersdk/wsjson/decoder.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
package wsjson | ||
import ( | ||
"context" | ||
"encoding/json" | ||
"sync/atomic" | ||
"nhooyr.io/websocket" | ||
"cdr.dev/slog" | ||
) | ||
type Decoder[T any] struct { | ||
conn *websocket.Conn | ||
typ websocket.MessageType | ||
ctx context.Context | ||
cancel context.CancelFunc | ||
chanCalled atomic.Bool | ||
logger slog.Logger | ||
} | ||
// Chan starts the decoder reading from the websocket and returns a channel for reading the | ||
// resulting values. The chan T is closed if the underlying websocket is closed, or we encounter an | ||
// error. We also close the underlying websocket if we encounter an error reading or decoding. | ||
func (d *Decoder[T]) Chan() <-chan T { | ||
if !d.chanCalled.CompareAndSwap(false, true) { | ||
panic("chan called more than once") | ||
} | ||
values := make(chan T, 1) | ||
go func() { | ||
defer close(values) | ||
defer d.conn.Close(websocket.StatusGoingAway, "") | ||
for { | ||
// we don't use d.ctx here because it only gets canceled after closing the connection | ||
// and a "connection closed" type error is more clear than context canceled. | ||
typ, b, err := d.conn.Read(context.Background()) | ||
spikecurtis marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
if err != nil { | ||
// might be benign like EOF, so just log at debug | ||
d.logger.Debug(d.ctx, "error reading from websocket", slog.Error(err)) | ||
return | ||
} | ||
if typ != d.typ { | ||
d.logger.Error(d.ctx, "websocket type mismatch while decoding") | ||
return | ||
} | ||
var value T | ||
err = json.Unmarshal(b, &value) | ||
if err != nil { | ||
d.logger.Error(d.ctx, "error unmarshalling", slog.Error(err)) | ||
return | ||
} | ||
select { | ||
case values <- value: | ||
// OK | ||
case <-d.ctx.Done(): | ||
return | ||
} | ||
} | ||
}() | ||
return values | ||
} | ||
// nolint: revive // complains that Encoder has the same function name | ||
func (d *Decoder[T]) Close() error { | ||
err := d.conn.Close(websocket.StatusNormalClosure, "") | ||
d.cancel() | ||
return err | ||
} | ||
// NewDecoder creates a JSON-over-websocket decoder for type T, which must be deserializable from | ||
// JSON. | ||
func NewDecoder[T any](conn *websocket.Conn, typ websocket.MessageType, logger slog.Logger) *Decoder[T] { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
return &Decoder[T]{conn: conn, ctx: ctx, cancel: cancel, typ: typ, logger: logger} | ||
} |
42 changes: 42 additions & 0 deletionscodersdk/wsjson/encoder.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package wsjson | ||
import ( | ||
"context" | ||
"encoding/json" | ||
"golang.org/x/xerrors" | ||
"nhooyr.io/websocket" | ||
) | ||
type Encoder[T any] struct { | ||
conn *websocket.Conn | ||
typ websocket.MessageType | ||
} | ||
func (e *Encoder[T]) Encode(v T) error { | ||
w, err := e.conn.Writer(context.Background(), e.typ) | ||
if err != nil { | ||
return xerrors.Errorf("get websocket writer: %w", err) | ||
} | ||
defer w.Close() | ||
j := json.NewEncoder(w) | ||
err = j.Encode(v) | ||
if err != nil { | ||
return xerrors.Errorf("encode json: %w", err) | ||
} | ||
return nil | ||
} | ||
func (e *Encoder[T]) Close(c websocket.StatusCode) error { | ||
return e.conn.Close(c, "") | ||
} | ||
// NewEncoder creates a JSON-over websocket encoder for the type T, which must be JSON-serializable. | ||
// You may then call Encode() to send objects over the websocket. Creating an Encoder closes the | ||
// websocket for reading, turning it into a unidirectional write stream of JSON-encoded objects. | ||
func NewEncoder[T any](conn *websocket.Conn, typ websocket.MessageType) *Encoder[T] { | ||
// Here we close the websocket for reading, so that the websocket library will handle pings and | ||
// close frames. | ||
_ = conn.CloseRead(context.Background()) | ||
return &Encoder[T]{conn: conn, typ: typ} | ||
} |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.