-
Notifications
You must be signed in to change notification settings - Fork 896
fix(coderd): fix memory leak in watchWorkspaceAgentMetadata
#10685
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
Changes from 1 commit
e6ad02f
65a9899
ab3cea2
1da56e6
5bb2a4b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -1767,10 +1767,10 @@ func (api *API) workspaceAgentUpdateMetadata(ctx context.Context, workspaceAgent | |
|
||
datum := database.UpdateWorkspaceAgentMetadataParams{ | ||
WorkspaceAgentID: workspaceAgent.ID, | ||
Key: []string{}, | ||
Value: []string{}, | ||
Error: []string{}, | ||
CollectedAt: []time.Time{}, | ||
Key: make([]string, 0, len(req.Metadata)), | ||
Value: make([]string, 0, len(req.Metadata)), | ||
Error: make([]string, 0, len(req.Metadata)), | ||
CollectedAt: make([]time.Time, 0, len(req.Metadata)), | ||
} | ||
|
||
for _, md := range req.Metadata { | ||
|
@@ -1835,22 +1835,28 @@ func (api *API) workspaceAgentUpdateMetadata(ctx context.Context, workspaceAgent | |
// @Router /workspaceagents/{workspaceagent}/watch-metadata [get] | ||
// @x-apidocgen {"skip": true} | ||
func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Request) { | ||
var ( | ||
ctx = r.Context() | ||
workspaceAgent = httpmw.WorkspaceAgentParam(r) | ||
log = api.Logger.Named("workspace_metadata_watcher").With( | ||
slog.F("workspace_agent_id", workspaceAgent.ID), | ||
) | ||
// Allow us to interrupt watch via cancel. | ||
ctx, cancel := context.WithCancel(r.Context()) | ||
defer cancel() | ||
r = r.WithContext(ctx) // Rewire context or SSE cancellation. | ||
|
||
workspaceAgent := httpmw.WorkspaceAgentParam(r) | ||
log := api.Logger.Named("workspace_metadata_watcher").With( | ||
slog.F("workspace_agent_id", workspaceAgent.ID), | ||
) | ||
|
||
// Send metadata on updates, we must ensure subscription before sending | ||
// initial metadata to guarantee that events in-between are not missed. | ||
update := make(chan workspaceAgentMetadataChannelPayload, 1) | ||
cancelSub, err := api.Pubsub.Subscribe(watchWorkspaceAgentMetadataChannel(workspaceAgent.ID), func(_ context.Context, byt []byte) { | ||
if ctx.Err() != nil { | ||
return | ||
} | ||
|
||
var payload workspaceAgentMetadataChannelPayload | ||
err := json.Unmarshal(byt, &payload) | ||
if err != nil { | ||
api.Logger.Error(ctx, "failed to unmarshal pubsub message", slog.Error(err)) | ||
log.Error(ctx, "failed to unmarshal pubsub message", slog.Error(err)) | ||
return | ||
} | ||
|
||
|
@@ -1859,17 +1865,16 @@ func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Requ | |
select { | ||
case prev := <-update: | ||
// This update wasn't consumed yet, merge the keys. | ||
newKeysSet := make(map[string]struct{}) | ||
for _, key := range payload.Keys { | ||
newKeysSet[key] = struct{}{} | ||
} | ||
keys := prev.Keys | ||
prevKeysSet := make(map[string]struct{}, len(prev.Keys)) | ||
for _, key := range prev.Keys { | ||
if _, ok := newKeysSet[key]; !ok { | ||
keys = append(keys, key) | ||
prevKeysSet[key] = struct{}{} | ||
} | ||
for _, key := range payload.Keys { | ||
if _, ok := prevKeysSet[key]; !ok { | ||
prev.Keys = append(prev.Keys, key) | ||
} | ||
} | ||
payload.Keys = keys | ||
payload.Keys = prev.Keys | ||
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. This is the actual memory leak (logic bug). |
||
default: | ||
} | ||
// This can never block since we pop and merge beforehand. | ||
|
@@ -1891,12 +1896,22 @@ func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Requ | |
} | ||
// Prevent handler from returning until the sender is closed. | ||
defer func() { | ||
cancel() | ||
<-sseSenderClosed | ||
}() | ||
// Synchronize cancellation from SSE -> context, this lets us simplify the | ||
// cancellation logic. | ||
go func() { | ||
select { | ||
case <-ctx.Done(): | ||
case <-sseSenderClosed: | ||
cancel() | ||
} | ||
}() | ||
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. These changes were added so that we can be sure we're not blocking on |
||
|
||
// We always use the original Request context because it contains | ||
// the RBAC actor. | ||
md, err := api.Database.GetWorkspaceAgentMetadata(ctx, database.GetWorkspaceAgentMetadataParams{ | ||
initialMD, err := api.Database.GetWorkspaceAgentMetadata(ctx, database.GetWorkspaceAgentMetadataParams{ | ||
WorkspaceAgentID: workspaceAgent.ID, | ||
Keys: nil, | ||
}) | ||
|
@@ -1908,15 +1923,22 @@ func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Requ | |
return | ||
} | ||
|
||
log.Debug(ctx, "got initial metadata", "num", len(initialMD)) | ||
|
||
metadataMap := make(map[string]database.WorkspaceAgentMetadatum) | ||
for _, datum := range md { | ||
for _, datum := range initialMD { | ||
metadataMap[datum.Key] = datum | ||
} | ||
//nolint:ineffassign // Release memory. | ||
initialMD = nil | ||
|
||
var lastSend time.Time | ||
sendMetadata := func() { | ||
lastSend = time.Now() | ||
values := maps.Values(metadataMap) | ||
|
||
log.Debug(ctx, "sending metadata", "num", len(values)) | ||
|
||
_ = sseSendEvent(ctx, codersdk.ServerSentEvent{ | ||
Type: codersdk.ServerSentEventTypeData, | ||
Data: convertWorkspaceAgentMetadata(values), | ||
|
@@ -1935,10 +1957,11 @@ func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Requ | |
fetchedMetadata := make(chan []database.WorkspaceAgentMetadatum) | ||
go func() { | ||
defer close(fetchedMetadata) | ||
defer cancel() | ||
|
||
for { | ||
select { | ||
case <-sseSenderClosed: | ||
case <-ctx.Done(): | ||
return | ||
case payload := <-update: | ||
md, err := api.Database.GetWorkspaceAgentMetadata(ctx, database.GetWorkspaceAgentMetadataParams{ | ||
|
@@ -1952,20 +1975,24 @@ func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Requ | |
return | ||
} | ||
select { | ||
case <-sseSenderClosed: | ||
case <-ctx.Done(): | ||
return | ||
// We want to block here to avoid constantly pinging the | ||
// database when the metadata isn't being processed. | ||
case fetchedMetadata <- md: | ||
log.Debug(ctx, "fetched metadata update for keys", "keys", payload.Keys, "num", len(md)) | ||
} | ||
} | ||
} | ||
}() | ||
defer func() { | ||
<-fetchedMetadata | ||
}() | ||
|
||
pendingChanges := true | ||
for { | ||
select { | ||
case <-sseSenderClosed: | ||
case <-ctx.Done(): | ||
return | ||
case md, ok := <-fetchedMetadata: | ||
if !ok { | ||
|
@@ -1991,7 +2018,7 @@ func (api *API) watchWorkspaceAgentMetadata(rw http.ResponseWriter, r *http.Requ | |
|
||
func convertWorkspaceAgentMetadata(db []database.WorkspaceAgentMetadatum) []codersdk.WorkspaceAgentMetadata { | ||
// An empty array is easier for clients to handle than a null. | ||
result := []codersdk.WorkspaceAgentMetadata{} | ||
result := make([]codersdk.WorkspaceAgentMetadata, 0, len(db)) | ||
for _, datum := range db { | ||
result = append(result, codersdk.WorkspaceAgentMetadata{ | ||
Result: codersdk.WorkspaceAgentMetadataResult{ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -492,6 +492,11 @@ func (c *Client) WatchWorkspaceAgentMetadata(ctx context.Context, id uuid.UUID) | |
firstEvent = false | ||
} | ||
|
||
// Ignore pings. | ||
if sse.Type == ServerSentEventTypePing { | ||
continue | ||
} | ||
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. This was a bug in |
||
|
||
b, ok := sse.Data.([]byte) | ||
if !ok { | ||
return xerrors.Errorf("unexpected data type: %T", sse.Data) | ||
|
Uh oh!
There was an error while loading. Please reload this page.